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


using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;



int main() {
    int n, x, y, z, xres, yres, zres;
    cin >> n;
    vector<vector<int>> vec(n);

    while(n--) {
        vector<int> aux(3);
        cin >> aux.at(0) >> aux.at(1) >> aux.at(2);
        vec.push_back(aux);

    }
    for ( int i = 0; i < vec.size(); i++ ) {
        for (int j = 0; j < vec[i].size(); j++) {
            cout << vec.at(i).at(j) << " ";
            }
        cout << endl;
    }
    cout << vec.at(0).at(0);
    return 0;
}

Why do the for loops work but trying to access an element directly produces an out of range error which says that the vector is of size 0? I would think that the for loops also only put some numbers in place o i and j. The input is like this:

3
1 2 3
1 2 3
1 2 3
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
Aborted (core dumped)

  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl May 28 '23 at 12:49
  • `vector> vec(n);` creates a vector containing `n` vectors of `int`, each of which has size zero. Since all your operations on `vec` in the first loop use `.push_back()` the first `n` elements will always have size zero. So `vec.at(0)` will return a reference to a vector with no elements, and `vec.at(0).at(0)` will throw. – Peter May 28 '23 at 13:40

2 Answers2

2

Your vector initially has a size of three, and then you add three more items to it.

Try this

vector<vector<int>> vec; // initial size zero

while(n--) {
    vector<int> aux(3);
    cin >> aux.at(0) >> aux.at(1) >> aux.at(2);
    vec.push_back(aux); // add new item

}

or this

vector<vector<int>> vec(n); // initial size 3

for (int i = 0; i < vec.size(); ++i) {
    vector<int> aux(3);
    cin >> aux.at(0) >> aux.at(1) >> aux.at(2);
    vec[i] = aux;           // overwrite existing item

}
john
  • 85,011
  • 4
  • 57
  • 81
2

The initial vector you create contains n empty vectors:

vector<vector<int>> vec(n);

Later you push n nonempty vectors. After this the outer vector contains 2 * n vectors and the first n of these are empty.

You should use

vector<vector<int>> vec;
vec.reserve(n); // allocate the necessary storage, but the size remains 0 for now
while(n--)
{
    vector<int> aux(3);
    cin >> aux.at(0) >> aux.at(1) >> aux.at(2);
    vec.push_back(std::move(aux)); // std::move avoids a copy here
}

or

vector<vector<int>> vec(n, std::vector<int>(3));

// vec is completely allocated now; just fill existing elements
for (auto& v : vec)
{
    std::cin >> v[0] >> v[1] >> v[2];
}
fabian
  • 80,457
  • 12
  • 86
  • 114