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
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.
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));
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.
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
.
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
int
s with a value of 1
:
std::vector<std::vector<int>> v(10, std::vector<int>(10, 1));
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With