Jeswin Jacob Jeswin Jacob - 1 month ago 7
C++ Question

How do I access and print individual elements of a vector of vectors?

I tried building a 7*3 matrix, and then printing it's elements as it's values are initialized, but unfortunately the program terminates when run. If there is a simpler,more efficient way of doing the same process, please do tell.

vector< vector<int> > v1;
for(int i = 0;i < 7;i++)
{
for(int j = 0;j < 3;j++)
{
v1[i].push_back(i + j);
cout << v1[i][j] << " ";
}
cout << "\n";
}

Answer

You forget to initialize v1.

You may use the following:

std::vector<std::vector<int>> v1(7, std::vector<int>(3));
for (int i = 0; i != 7; ++i) {
    for (int j = 0; j != 3; ++j) {
        v1[i][j] = i + j;
    }
}

// Display
for (const auto& row : v1) {
    for (const auto& e : row) {
        std::cout << e << " ";
    }
    std::cout << "\n";
}