Ben Jenney
Ben Jenney

Reputation: 75

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.

Upvotes: 1

Views: 83

Answers (2)

R Sahu
R Sahu

Reputation: 206567

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'));

Upvotes: 1

xashru
xashru

Reputation: 3580

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);
}

Upvotes: 1

Related Questions