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
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!
#include <vector>
#include <iostream>
using namespace std;
int main(){
int n; cin >> n;
vector<vector<int>> v(n);
//populate
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
int number; cin >> number;
v[i].push_back(number);
}
}
// display
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << v[i][j] << " ";
}
cout << endl;
}
}
Input:
4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
Output:
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44