Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a vector of vectors having a fixed size with boost assign

Having a vector of vector with a fixed size,

vector<vector<int> > v(10);

I would like to initialize it so that it has in all elements a one dimensional vector with initialized value (for example 1).

I have used Boost Assign as follows

v = repeat(10,list_of(list_of(1)));

and I've got a compilation error

error: no matching function for call to ‘repeat(boost::assign_detail::generic_list<int>)’

Could you please tell me how to do that. Thanks in advance

like image 477
saloua Avatar asked Oct 29 '12 12:10

saloua


People also ask

How do you initialize a vector to a specific size?

You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.

How do you initialize a vector vector of given size in C++?

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 is the correct way to initialize vector in?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.


3 Answers

This doesn't use boost::assign but does what you need:

vector<vector<int>> v(10, vector<int>(10,1)); 

This creates a vector containing 10 vectors of int, each containing 10 ints.

like image 67
juanchopanza Avatar answered Oct 12 '22 22:10

juanchopanza


You don't need to use boost for the required behaviour. The following creates a vector of 10 vector<int>s, with each vector<int> containing 10 ints with a value of 1:

std::vector<std::vector<int>> v(10, std::vector<int>(10, 1)); 
like image 30
hmjd Avatar answered Oct 12 '22 23:10

hmjd


I will just try to explain it to those new to C++. A vector of verctors mat has the advantage that you can access its elements directly at almost no cost using the [] operator..

int n(5), m(8);
vector<vector<int> > mat(n, vector<int>(m));

mat[0][0] =4; //direct assignment OR

for (int i=0;i<n;++i)
    for(int j=0;j<m;++j){
        mat[i][j] = rand() % 10;
    }

Of course this is not the only way. And if you do not add or remove elements, one can also use the native containers mat[] which are nothing more than pointers. Here's my fav way, using C++:

int n(5), m(8);
int *matrix[n];
for(int i=0;i<n;++i){
    matrix[i] = new int[m]; //allocating m elements of memory 
    for(int j=0;j<m;++j) matrix[i][j]= rand()%10;
}

This way, you don't have to use #include <vector>. Hopefully, it's clearer!

like image 25
moldovean Avatar answered Oct 13 '22 00:10

moldovean