// // Defines a Vector in 3D Cartesian space with linear combinations, [] (norm), // * (dot product) and ^ (vector product). // #ifndef Vector_HPP #define Vector_HPP #include #include #include #include class Vector { // the vector data double x, y, z; public: // constructors Vector(): x(0), y(0), z(0) { } Vector(const Vector& v): x(v.x), y(v.y), z(v.z) { } Vector(double x0, double y0, double z0) : x(x0), y(y0), z(z0) { } // assignment Vector& assign(double x0, double y0, double z0) { x = x0; y = y0; z = z0; return *this; } // array access double& operator [](int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; } assert(false); return x; } const double& operator [](int i) const { switch (i) { case 0: return x; case 1: return y; case 2: return z; } assert(false); return x; } // math operators Vector operator - ( ) const { return Vector(-x, -y, -z); } Vector& operator += (const Vector& v) { x += v.x; y += v.y; z += v.z; return *this; } Vector& operator -= (const Vector& v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector& operator *= (double c) { x *= c; y *= c; z *= c; return *this; } Vector& operator /= (double c) { assert(c != 0.0); double inv = 1.0/c; x *= inv; y *= inv; z *= inv; return *this; } Vector operator + (const Vector& v) const { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator - (const Vector& v) const { return Vector(x - v.x, y - v.y, z - v.z); } Vector operator / (double c) const { assert(c != 0.0); return Vector(x/c, y/c, z/c); } bool operator == (const Vector& v) const { return ((x == v.x) && (y == v.y) && (z == v.z)); } bool operator != (const Vector& v) const { return (!(*this == v)); } // friends friend inline Vector operator * (double c, Vector const &v); friend inline Vector operator * (Vector const &v, double c); friend inline ostream& operator<< (ostream& out, Vector& v ); // vector metrics double dot (const Vector& v) const { return x*v.x + y*v.y + z*v.z; } Vector cross (const Vector& v) const { return Vector(y*v.z - z*v.y, -x*v.z + z*v.x, x*v.y - y*v.x); } double norm( ) const { return sqrt(x*x + y*y + z*z); } Vector unit( ) { double d=norm(); assert(d!=0.0); return Vector(x/d, y/d, z/d); } Vector& normalize( ) { double d=norm(); assert(d!=0.0); x/=d; y/=d; z/=d; return *this; } double dist(const Vector& v) const { return sqrt((x-v.x)*(x-v.x) + (y-v.y)*(y-v.y) + (z-v.z)*(z-v.z)); } // IO void read( FILE *fp ) { fscanf( fp, " %lf %lf %lf ", &x, &y, &z ); } void write( FILE *fp ) { fprintf( fp, "( %lf , %lf , %lf )", x, y, z ); } }; inline ostream& operator<< (ostream& out, Vector& v ) { return out << "( " << v.x << ", " << v.y << ", " << v.z << " )"; } inline Vector operator * (double c, Vector const &v) { return Vector(v.x*c, v.y*c, v.z*c); } inline Vector operator * (Vector const &v, double c) { return Vector(v.x*c, v.y*c, v.z*c); } #endif