简体   繁体   中英

How to initialize a const int 2-dimension vector in C++

How to initialize a const int 2-dimension vector:

Const int vector < vector < int > >  v ? 

v = {1 , 1 ; 1, 0}  ?

it does not work .

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).

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), eg

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.

using namespace std;

int main(void){

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

    return 0;

}

Initialises a 10x10 array to 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM