# vector product

Discussion in 'C++' started by Bernhard Hidding, Apr 22, 2004.

1. ### Bernhard HiddingGuest

Hello,
I'm a beginner in c++ and I would like to implement some math operations
into my program. Explicitly, would like to perform cross product
calculations. Is there some library or predefined function that is capable
to do this or do I have to write a function that can calculate vector
products for myself? Furthermore, what data structure should I use?
Bernhard Hidding

Bernhard Hidding, Apr 22, 2004

2. ### Karl Heinz BucheggerGuest

Bernhard Hidding wrote:
>
> Hello,
> I'm a beginner in c++ and I would like to implement some math operations
> into my program. Explicitly, would like to perform cross product
> calculations. Is there some library or predefined function that is capable
> to do this or do I have to write a function that can calculate vector
> products for myself? Furthermore, what data structure should I use?

You have to do your own vector/matrix library.
Alternatively you can search the web for one. That really
depends on what operations you need. A simple 3D vector
class could look like this:

const double EPSILON = 0.000001;

struct CVector
{
public:
CVector() : X(0), Y(0), Z(0) {}
CVector ( double x, double y, double z ) : X(x), Y(y ), Z(z) { }

CVector operator + (const CVector& v ) const
{ return CVector( X + v.X, Y + v.Y, Z + v.Z ); }
CVector operator - (const CVector& v ) const
{ return CVector( X - v.X, Y - v.Y, Z - v.Z ); }
CVector operator -() const
{ return CVector( -X, -Y, -Z ); }
BOOL operator == (const CVector& v) const
{ return (fabs(X - v.X) < EPSILON) &&
(fabs(Y - v.Y) < EPSILON) &&
(fabs(Z - v.Z) < EPSILON); }
BOOL operator != (const CVector& v) const
{ return ! (*this == v); }
const CVector& operator += (const CVector& v)
{ X += v.X; Y += v.Y; Z += v.Z; return *this; }
const CVector& operator -= (const CVector& v)
{ X -= v.X; Y -= v.Y; Z -= v.Z; return *this; }
const CVector& operator *= (const CVector& v)
{ X *= v.X; Y *= v.Y; Z *= v.Z; return *this; }

CVector CrossProd( const CVector& v ) const
{ return CVector( Y * v.Z - Z * v.Y,
Z * v.X - X * v.Z,
X * v.Y - Y * v.X ); }
float DotProd( const CVector& v ) const
{ return X * v.X + Y * v.Y + Z * v.Z; }
void Set( double x, double y, double z ) { X = x; Y = y; Z = z; }
void Get( double& x, double& y, double& z ) const { x = X; y = Y; z = Z; }
double Norm() const
{ return ( X*X ) + ( Y*Y ) + (Z*Z);}
double Length() const
{ return sqrt( Norm() ); }
double Distance( const CVector& v ) const
{ return (v - *this).Length(); }

double X;
double Y;
double Z;
};

--
Karl Heinz Buchegger

Karl Heinz Buchegger, Apr 22, 2004