Reputation: 5040
How to initialize a const int 2-dimension vector:
Const int vector < vector < int > > v ?
v = {1 , 1 ; 1, 0} ?
it does not work .
Upvotes: 3
Views: 454
Reputation: 75150
If your compiler supports the initialisation-list feature (is that what it's called?) of C++11, you can do this:
const vector<vector<int>> v {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Note that you won't be able to add any elements to the first dimension (but you can add elements to the second), e.g.
v.push_back(vector<int> { 8, 9, 10 }); // BAD
v[0].push_back(4); // OK
If you wanted the second dimension to be non-modifiable, you'd do
vector<const vector<int>> {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Then
v.push_back(const vector<int> { 8, 9, 10 }); // OK
v[0].push_back(4); // BAD
OR if you want the elements themselves to be const
, you would do
vector<vector<const int>> {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Then
v.push_back(vector<const int> { 8, 9, 10 }); // OK
v[0].push_back(4); // OK
v[0][0] = 2; // BAD
You probably want to modify it at runtime, so it's probably good to remove the const
altogether.
Upvotes: 5
Reputation:
using namespace std;
int main(void){
const vector< vector<int> > v(10, vector<int>(10,1));
return 0;
}
Initialises a 10x10 array to 1
Upvotes: 0
Reputation: 361612
You can do this (only in C++11):
const vector<vector<int>> v{{1,2,3},{4,5,6}};
Also note that you don't need to write > >
. As this issue has been fixed in C++11, >>
would work. It wouldn't be interpreted as right-shift operator (as was the case with C++03).
Upvotes: 6