Search code examples
c++vectorinitializationmemberunique-ptr

Initializing templated matrix class with unique pointer member to vector of vectors


I have

template<class T>
class Matrix{
public:
Matrix();
~Matrix();

private:
std::unique_ptr<std::vector<std::vector<T> > > PtrToMyMatrix;

};

I have difficulty with initializing PtrToMyMatrix. Suppose that the constructor should only put in PtrToMyMatrix a pointer to a 1x1 matrix of a T. How do I write this?

I suppose it is something like

Matrix<T>::Matrix():PtrToMyMatrix(//Here it goes the value
){};

In the place of the value I suppose it should go something like

new std::unique_ptr<vector<vector<T> > >(// Here a new matrix
)

In the place of the new matrix I suppose it goes something like

new vector<vector<T> >(// Here a new vector
)

In the place of the new vector

new vector<T>(new T())

How should it be?


Solution

  • I think you're after this:

    std::unique_ptr<std::vector<std::vector<T> > >
        PtrToMyMatrix(new std::vector<std::vector<T> >(1, std::vector<T>(1)));
    

    The constructor is std::vector(size_type n, const value_type& val); (alloc missing).

    So you construct the outer vector with 1 inner vector that is constructed with 1 T.

    However it is very rarely necessary to create std::vector dynamically as it already stors its internal data dynamically. You would usually just instantiate it by value:

    std::vector<std::vector<T> > MyMatrix(1, std::vector<T>(1));