Challenge: Vector Algebra

Test the skills you learned in this section by performing basic mathematical operations on vectors.

We'll cover the following

Problem statement

Handling and manipulating different data structures is important, especially when performing complex mathematical computations. You are tasked to implement basic vector operations like addition, subtraction, multiplication, scalar multiplication, and dot product of the numeric vector objects. You must add size checking—the vectors being operated on have the same size—to any other implementation to create a robust vector class.

Note: We can use the code implementationVector_Class_Implementation provided in this section as a starting point.

Analysis

We can extract the following information from the problem statement:

  • Vector operations: Implement the following vector operations:

    • The vector_add operation: Performs element-wise addition between two vectors of the same size. Also, overloads the + operator for easier access.

    • The vector_sub operation: Performs element-wise subtraction between two vectors of the same size. Also, overloads the - operator for easier access.

    • The vector_mul operation: Performs element-wise multiplication between two vectors of the same size. Also, overloads the * operator for easier access.

    • The vector_scalar_mul operation: Performs element-wise multiplication between a numeric value and a vector. Also, overloads the * operator for easier access.

    • The vector_dot operation: Calculates the dot product between two vectors of the same size.

  • Size compatibility: Make sure the vectors you operate on are the same size, except for scalar multiplication. If the sizes aren’t the same, std::runtime_error is thrown with the message “The vector size is incompatible for this operation.”

Note: Make use of the concepts of exception handling to handle errors caused by incompatible vector sizes.

Let’s make the problem clearer with the following figure:

Get hands-on with 1200+ tech skills courses.