Basic Euclidean vector operations in C++

Euclidean vectors are very important quantity in mathematics, applied mathematics, physics, engineering etc. Formally vectors are those quantities which have both magnitude and direction. For example velocity. Velocity has both magnitude (Speed, like 2 Km/Hr) and direction (e.g. east). In the programmer’s perspective, there are many situation where you need to compute different vector operations. For example, consider a moving ball. To simulate the motion of ball, you must calculate the velocity of the ball. The ball has both magnitude (i.e rate of translation of position of center of the ball) and direction (e.g. axis x or y or z). This is just one example but there are various examples where vector operations are essential.
Now in this article, I will show you how to compute different vector operations like sum of two vectors, multiplication by scalar, dot product, cross product, normalization etc in C++. I choose C++ instead of C because it is object oriented. The vector can be represented by an object. The components of vector along x, y and z-axis will be the data member of the object. The data members are attributes of the object. Similarly, different operations will be the member functions of the object. Now the vector object can completely represent the vector quantity.

In this program, I have implemented as many vector operations as I can. For example summation of two vectors, difference of two vectors, magnitude, normalization of a vector, dot product and cross product of two vectors, multiplication and division by scalar quantity etc. Since vector is a user-defined data type (class) , treating them as a standard data type and trying to use built-in operations like +, –,*, / will result in error. For this, I have implemented operator overloading feature of C++. In this program, you will notice following operator overloaded

  1. index []
  2. Addition +
  3. Subtraction  –
  4. Multiplication *
  5. Division –
  6. Extraction <<
  7. +=, –=, *=, /=
  8. Unary – and +

Source Code:

Sample Output

Same technique can be implemented to computer other quantities like Complex numbers, Matrix etc.

If you have any queries, please ask in the form of comment.

SHARE Basic Euclidean vector operations in C++

You may also like...

2 Responses

  1. Thanks for sharing such a nice post

  2. Can you please let me know some more programming things

Leave a Reply

Your email address will not be published. Required fields are marked *