1

I want to implement Vector and Matrix classes in C++, such that Vector and Matrix objects are able to be multiplied. There are the following 2 structures that I could think of for their implementations:

  1. Implement the template class Vector with T* type of data, and then define template class Matrix as an array of Vectors.

  2. Implement the template class Matrix with T** type of data, and then inherit template class Vector as a Matrix with (number of columns = 1).

The disadvantage of the 1st approach is that, Vector class doesn't take care of column and row vectors and the vector-vector multiplications would be problematic, and in second approach, the Vector would be treated as a 2D Matrix with (number of columns =1) or T**.

What would be the best way to implement these 2 classes? Thanks.

Evg
  • 25,259
  • 5
  • 41
  • 83
RTn Saberpour
  • 53
  • 1
  • 1
  • 5
  • 6
    Neither approach is good. Matrices should be implemented as a *contiguous* array, i.e. a `T*` (or, more cleanly, a `std:vector`). This gives you contiguous storage, and your `Matrix` class handles the index calculation. – Konrad Rudolph Jun 20 '20 at 14:06
  • 3
    See [this answer](https://stackoverflow.com/a/2076668). – Evg Jun 20 '20 at 14:12

1 Answers1

2

I wouldn't recommend doing to much stuff with raw pointers, it can get really messy later on and is a nightmare to debug. I would use a generic vector

template<typename T>
std::vector<T>

so you can use different types if you need to. But if you are only dealing with number I wouldn't over-engineer it.

For the multiplication you can use operator overloading. You could look at same already existing implementation and see if there is something that suits your needs. A quick google research gave me this:

CodeProject

If you find anything else feel free to add it to your question so nobody has to reinvent the wheel.

SchnJulian
  • 182
  • 1
  • 11