Search code examples
c++multidimensional-arrayvector

Double vector out of range


#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)


Solution

  • 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];
    }