2d平面向量计算

PlaneVector.hpp

#ifndef PlaneVector_h__
#define PlaneVector_h__

template<typename coordinate_type>
struct PlaneVector
{
	coordinate_type x;
	coordinate_type y;
};

template<typename coordinate_type>
std::ostream& operator<<(std::ostream& out, const PlaneVector<coordinate_type>& pt) {
	out << '(' << pt.x << ',' << pt.y << ')';
	return out;
}

/*!
	向量加法
	首尾相连,连接首尾,指向终点
*/
template<typename coordinate_type>
PlaneVector<coordinate_type> add(const PlaneVector<coordinate_type>& p1, const PlaneVector<coordinate_type>& p2)
{
	return (p1.x + p2.x, p1.y + p2.y);
}

/*!
	向量减法
	同起点,指被减(减向量终点指向被减向量终点)
*/
template<typename coordinate_type>
PlaneVector<coordinate_type> sub(const PlaneVector<coordinate_type>& p1, const PlaneVector<coordinate_type>& p2)
{
	return (p1.x - p2.x, p1.y - p2.y);
}

/*!
	点乘
	a * b = |a||b|cosθ
	a·b>0    方向基本相同,向量夹角为锐角
	a·b=0    正交,相互垂直
	a·b<0    方向基本相反,向量夹角为钝角
*/
template<typename coordinate_type>
coordinate_type dotProduct(const PlaneVector<coordinate_type>& p1, const PlaneVector<coordinate_type>& p2)
{
	return p1.x * p2.x + p1.y * p2.y;
}

/*!
	叉乘
	a ^ b = |a||b|sinθ
	共起点向量 a 和 向量 b 所构成平行四边形的面积
*/
template<typename coordinate_type>
PlaneVector<coordinate_type> crossProduct(const PlaneVector<coordinate_type>& p1, const PlaneVector<coordinate_type>& p2)
{
	return (p1.y * 0 - 0 * p2.y, 0 * p2.x - p1.x * 0);
}

#endif // PlaneVector_h__

posted @ 2021-03-04 10:18  學海無涯  阅读(140)  评论(0编辑  收藏  举报