///
/// vector.h
///
///
#ifndef VECTOR_H
#define VECTOR_H
// A Vector in space
struct Vector
{
public:
double x;
double y;
double z;
Vector operator- ();
Vector operator* ( const double d );
Vector operator/ ( const double d );
Vector operator+= ( const Vector& v );
Vector operator-= ( const Vector& v );
Vector operator*= ( const double d );
Vector operator/= ( const double d );
void operator++ ();
void operator-- ();
// Get the length of a Vector
double length();
// Get the unit Vector with length 1
Vector unit();
};
Vector operator+ ( const Vector& v1, const Vector& v2 );
Vector operator- ( const Vector& v1, const Vector& v2 );
double operator* ( const Vector& v1, const Vector& v2 );
// Return a Vector
Vector newVector( double x, double y, double z );
// Get the distance between two Vectors
double dist( Vector v1, Vector v2 );
// Create the cross product between a and b
Vector crossproduct( Vector a, Vector b );
# endif // VECTOR_H
///
/// vector.cpp
///
///
#include "vector.h"
#include <cmath>
Vector operator+ ( const Vector& v1, const Vector& v2 )
{
return newVector( v1.x + v2.x, v1.y + v2.y, v1.z + v2.z );
}
Vector operator- ( const Vector& v1, const Vector& v2 )
{
return newVector( v1.x - v2.x, v1.y - v2.y, v1.z - v2.z );
}
double operator* ( const Vector& v1, const Vector& v2 )
{
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
Vector Vector::operator- ()
{
return newVector( -this->x, -this->y, -this->z );
}
Vector Vector::operator* ( const double d )
{
return newVector( this->x * d, this->y * d, this->z * d );
}
Vector Vector::operator/ ( const double d )
{
return newVector( this->x / d, this->y / d, this->z / d );
}
Vector Vector::operator+= ( const Vector& v )
{
*this = *this + v;
return *this;
}
Vector Vector::operator-= ( const Vector& v )
{
*this = *this - v;
return *this;
}
Vector Vector::operator*= ( const double d )
{
*this = *this * d;
return *this;
}
Vector Vector::operator/= ( const double d )
{
*this = *this / d;
return *this;
}
void Vector::operator++ ()
{
*this += this->unit();
}
void Vector::operator-- ()
{
*this -= this->unit();
}
// Return a Vector
Vector newVector( double x, double y, double z )
{
Vector v;
v.x = x;
v.y = y;
v.z = z;
return v;
}
// Get the length of a Vector
double Vector::length()
{
return sqrt( this->x*this->x + this->y*this->y + this->z*this->z );
}
Vector Vector::unit()
{
return *this / this->length();
}
// Get the distance between two Vectors
double dist( Vector v1, Vector v2 )
{
return sqrt( (v2.x-v1.x)*(v2.x-v1.x) + (v2.y-v1.y)*(v2.y-v1.y) + (v2.z-v1.z)*(v2.z-v1.z) );
}
// Create the cross product between a and b
Vector crossproduct( Vector a, Vector b )
{
return newVector( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x );
}
/// End of vector.cpp
///