vector subscript out of range for vector of vectors

41 views Asked by At

Here's the code:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::vector<std::string>> gridOfStars(20);
    std::vector<std::string> gridRow(20);

    for (int i = 0; i < 20; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            gridRow.push_back(" * ");
        }
        gridOfStars.push_back(gridRow);
    }

    for (int i = 0; i < gridOfStars.size(); i++)
    {
        for (int j = 0; j < gridRow.size(); j++)
        {
            std::cout << gridOfStars[i][j];
        }
        std::cout << '\n';
    }
    return 0;
}

It keeps giving me an exception that says the vector subscript is out of range. I think that means that the size of the whole vector (which should be 20x20) is less than the integers i and j should be.

I tried to change int i (or j) = 0 to 1 and changing < to <=, didn't work. I also tried changing the size of the vectors to be bigger. Before this I didn't have a preset size, and it still didn't work, but it only printed the first row of asterisks.

EDIT: I think it also might have something to do with using gridRow.

Also I added gridRow.clear() to the end of the outermost first for loop and that ran the code and made 20 lines of nothing, no stars. (I also added a string called input and an input request before return 0 so that I could see it.) I thought that gridRow would be copied into the gridOfStars vector and then so it didn't matter that gridRow would be erased, no?

EDIT2: changing the vector into an array makes another error: access reading memory violation.

0

There are 0 answers