C++ – Initialization of a Vector of Vectors

c++matrixstlvector

Is there a way to initialize a vector of vectors in the same ,quick, manner as you initialize a matrix?

typedef int type;

type matrix[2][2]=
{
{1,0},{0,1}
};

vector<vector<type> > vectorMatrix;  //???

Best Answer

For the single vector you can use following:

typedef int type;
type elements[] = {0,1,2,3,4,5,6,7,8,9};
vector<int> vec(elements, elements + sizeof(elements) / sizeof(type) );

Based on that you could use following:

type matrix[2][2]=
{
   {1,0},{0,1}
};

vector<int> row_0_vec(matrix[0], matrix[0] + sizeof(matrix[0]) / sizeof(type) );

vector<int> row_1_vec(matrix[1], matrix[1] + sizeof(matrix[1]) / sizeof(type) );

vector<vector<type> > vectorMatrix;
vectorMatrix.push_back(row_0_vec);
vectorMatrix.push_back(row_1_vec);

In c++0x, you be able to initialize standard containers in a same way as arrays.

Related Question