简体   繁体   中英

filling a vector of vectors initialized with unspecified dimensions

I have created a 2d vector that is filled with '0's as it is initialized:

std::vector<std::vector<char>> grid(rows, std::vector<char>(cols, '0'));

however I would like to initialize it as an empty 2d vector with unspecified size:

std::vector<std::vector<char>>grid;

and then fill it to achieve the same effect as the first statement. I do not think I can use fill() because it has no .begin() or .end() and I have been playing with for loops and push_back to no avail, usually get a segmentation fault error . I feel that what I am trying to do should be possible, and if it is what is the best way to go about doing it? Any help would be greatly appreciated. Thank you.

You can do this with couple of for loops.

std::vector<std::vector<char>>grid;
for(int i=0; i<rows; i++) {
    vector<char> v;
    for(int j=0; j<cols; j++) {
        char ch;
        cin >> ch;
        v.push_back(ch);
    }
    grid.push_back(v);
}

If you are able to use C++11 or higher, you can use the following overload of std::vector::resize() :

void resize( size_type count, const value_type& value );

For your case, it will be:

std::vector<std::vector<char>>grid;

...

grid.resize(rows, std::vector<char>(cols, '0'));

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