向量基本用法模版

#include<cstdio>
#include<cmath>
using namespace std;

struct Point {
    double x, y;
    Point (double x=0, double y=0):x(x), y(y){}
};
typedef Point Vector;
//重载向量间的加减乘除
Vector operator + (Vector A, Vector B){ return Vector(A.x+B.x, A.y+B.y); }
Vector operator - (Point A, Point B){ return Vector(A.x-B.x, A.y-B.y); }
Vector operator * (Vector A, double p){ return Vector(A.x*p, A.y*p); }
Vector operator / (Vector A, double p){ return Vector(A.x/p, A.y/p); }

Point read_point(){//读入点
    Point p;
    scanf("%lf%lf", &p.x, &p.y);
    return p;
}
double Dot(Vector A, Vector B){return A.x*B.x+A.y*B.y; }//A,B点乘
double Length(Vector A){ return sqrt(Dot(A, A)); }//求向量长度

double Angle(Vector A, Vector B){//求两向量夹角
    return acos(Dot(A, B)/Length(A)/Length(B));
}

Vector Rotate(Vector A, double rad){//向量A逆时针转rad后的向量值
    return Vector(A.x*cos(rad)-A.y*sin(rad), A.x*sin(rad)+A.y*cos(rad));
}

double Cross(Vector v1, Vector v2){//叉乘
    return v1.x*v2.y-v1.y*v2.x;
}
Point GetLineIntersection(Point A, Vector v1, Point B, Vector v2){//求在点v1上的向量A和在点v2上的向量B的交点
    Vector v3=A-B;
    double t=Cross(v2, v3)/Cross(v1, v2);
    return A+v1*t;
}
double DistanceToLine(Point P,Point A,Point B){//点P到线A,B的距离
    Vector v1=B-A;
    Vector v2=P-A;
    return fabs(Cross(v1,v2)/Length(v1));
}
Point GetLineProjection(Point P,Point A,Point B){//点P到线A,B的投影的点
    Vector v=B-A;
    return A+v*(Dot(v,P-A)/Dot(v,v));
}
const double eps=1e-10;//判断浮点数和0的关系
int dcmp(double x){
    if(fabs(x)<eps)return 0;
    else return x<0?-1:1;
}
bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2){//判断线a1,b1和线a2,b2是否相交或判断两点是否同侧
    double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
    double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
    return dcmp(c1)*dcmp(c2)<0&&dcmp(c3)*dcmp(c4)<0;
}
double ConvexArea(Point *p,int n){//tu多边形有向面积
    double area=0;
    for(int i=1;i<n-1;i++){
        area+=Cross(p[i]-p[0], p[i+1]-p[0]);
    }
    return area/2;
}

猜你喜欢

转载自blog.csdn.net/xiao_you_you/article/details/89429455