Quote:Original post by Zael
I am trying to implement a matrix class which contains a 2D vector and has methods for matrix operations in the class. At the moment I am having issue with either the initialization or the output function
Without trying to debug it, I will tell you that you can
do the initialization much more simply, by taking advantage of the constructors that std::vector provides:
template <class T>Matrix<T>::Matrix(unsigned int cols, unsigned int rows, T values) : mat(cols, vector<T>(rows, values)) {}template <class T>vector<vector<T> > matrix(unsigned int cols, unsigned int rows, T values) { return vector<vector<T> >(cols, vector<T>(rows, values));}
By the way, it is never useful to .clear() a standard library container in the constructor (unless you put elements into it earlier in the constructor that you have to get rid of; but it's hard to imagine how that would happen). Constructors are called for all data members and bases of a class before the class' own constructor is called. If you don't specify which one (by using the initialization list, as shown above), the default constructor is used. For standard library containers, that initializes the container as an "empty" one with zero initial elements. Similarly, it is never useful to .clear() the standard library container in the
destructor (unless... well, it would have to be something even weirder), because the container's destructor will be called afterward, effectively .clear()ing the container anyway.
Oh, and if you really want this kind of multiple-dimensional,
rectangular array functionality, don't build it yourself; use boost::multi_array. It's more efficient anyway (because it doesn't have the flexibility in the underlying data to allow each "row" to be a different length, and therefore does not carry the overhead needed to make that possible).