Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of a vector of vectors?

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;  //???
like image 860
Eric Avatar asked Jun 17 '10 11:06

Eric


People also ask

How do you initialize a vector vector?

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));

What does it mean to initialize a vector?

What Does Initialization Vector Mean? An initialization vector is a random number used in combination with a secret key as a means to encrypt data. This number is sometimes referred to as a nonce, or “number occuring once,” as an encryption program uses it only once per session.


2 Answers

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.

like image 197
sinek Avatar answered Oct 07 '22 00:10

sinek


std::vector<std::vector<int>> vector_of_vectors;

then if you want to add, you can use this procedure:

vector_of_vectors.resize(#rows); //just changed the number of rows in the vector
vector_of_vectors[row#].push_back(someInt); //this adds a column

Or you can do something like this:

std::vector<int> myRow;
myRow.push_back(someInt);
vector_of_vectors.push_back(myRow);

So, in your case, you should be able to say:

vector_of_vectors.resize(2);
vector_of_vectors[0].resize(2);
vector_of_vectors[1].resize(2);
for(int i=0; i < 2; i++)
 for(int j=0; j < 2; j++)
   vector_of_vectors[i][j] = yourInt;
like image 41
Brett Avatar answered Oct 06 '22 23:10

Brett