ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

自主开发,计算几何常用二维向量类 vector_2d

2022-06-04 14:01:39  阅读:122  来源: 互联网

标签:Tp 2d vector tp2 tp1 public 向量


支持的东西:

向量加减,数乘,点积,叉积,夹角计算,垂直、平行判断,向量旋转,模长计算。

注意如果要使用判断功能要先设定 eps 精度值,或者直接外置 eps 常数。

还有就是重载类型选浮点型,要不然会直接上天。

欢迎各位读者提供改进意见(正确性修正,常数优化,精度优化等),您的意见会被记录在此。

第一版。

参考资料:OI-wiki 向量,感谢!


template<class Tp>//float or double or long double
class vector_2d{
		
	public: Tp x,y;
	
	public: Tp eps;
	
	public: Tp myabs(Tp t){
		return (t>0.0)?(t):(-t);
	}
	
	public: void seteps(Tp neps){//精度设置
		eps=neps;
	}
	
	public: void build(Tp tx,Tp ty){
		x=tx;y=ty;
	}
		
	public: Tp length(){//模长计算
		return sqrt(x*x+y*y);
	}
		
	public: void rotate(Tp theta){//+theta,逆时针旋转
		vector_2d<Tp>res;
		res.build(x*cos(theta)-y*sin(theta),y*cos(theta)+x*sin(theta));
		x=res.x;y=res.y;
	}
		
	public: void multiply(Tp lamda){//数乘
		x*=lamda;y*=lamda;
	}
	
	public: bool parallel(vector_2d tp2){//平行判断
		return myabs(((*this)^tp2))<eps;
	}
	
	public: bool perpendicular(vector_2d tp2){//垂直判断
		return myabs((*this)*tp2)<eps;
	}
	
	public: Tp angle(vector_2d tp2){//求夹角
		return acos((*this)*tp2/(*this).length()/tp2.length());
	}
	
	friend vector_2d operator + (vector_2d tp1,vector_2d tp2){
		vector_2d<Tp>res;
		res.build(tp1.x+tp2.x,tp1.y+tp2.y);
		return res;
	} 
	
	friend vector_2d operator - (vector_2d tp1,vector_2d tp2){
		vector_2d<Tp>res;
		res.build(tp1.x-tp2.x,tp1.y-tp2.y);
		return res;
	} 
	
	friend Tp operator * (vector_2d tp1,vector_2d tp2){//点积
		return tp1.x*tp2.x+tp1.y*tp2.y;
	}
	
	friend Tp operator ^ (vector_2d tp1,vector_2d tp2){//叉积
		return tp1.x*tp2.y-tp2.x*tp1.y;
	}
	
};

标签:Tp,2d,vector,tp2,tp1,public,向量
来源: https://www.cnblogs.com/Lucky-Yukikaze/p/16341782.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有