Reputation: 131
My aim is to populate a constant vector of vectors from an input stream.
I am able to do so and also print the constructed vector using the readVector()
method as shown below.
But when I try to access a particular value using the at()
routine of the std::vector
it produces the error out of bounds. I am not even able to access the [0, 0] element of the 2d vector although I am able to print the whole vector.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
inline const int myread() {
int n;
cin >> n;
return n;
}
const vector< vector <int> > readVector (const int &n) {
int i, j;
vector< vector <int> > v (n);
// Populate the vector v.
for (i = 0; i < n; i++) {
const int rs = myread(); // row size
// construct an internal vector (iv) for a row.
vector <int> iv(rs);
for (j = 0; j < rs; j++) {
cin >> iv[j];
}
// Append one row into the vector v.
v.push_back (iv);
}
return v;
}
int main() {
const int n = myread();
// Construct a 2d vector.
const vector< vector <int> > v (readVector (n));
// Prints the vector v correctly.
for (vector <int> k : v) {
for (int l : k) {
cout << l << " ";
}
cout << endl;
}
// Produces the out of bounds error shown below
cout << v.at(0).at(0);
return 0;
}
A run:
Input: (two rows with elements
1, 5, 4
and1, 2, 8, 9, 3
, respectively.)
2
3 1 5 4
5 1 2 8 9 3
Output:
1 5 4
1 2 8 9 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)
I am new to C++
. Please help me.
Upvotes: 0
Views: 170
Reputation: 4888
Another way to fix this is declaring an array of vector like this :
vector< int > v (n);
And then store the vector :
v[i].push_back (iv);
This helpful when you need to access vector by index later on.
Upvotes: 1
Reputation: 8527
The problem is that the line
vector< vector <int> > v (n);
already creates a vector containing n
vectors of int
each having a size of 0. The line
v.push_back (iv);
pushes your new vector after the empty vectors. You should either use an assignment or create an empty vector with
vector< vector <int> > v;
Just print the vector size
std::cout << v.size() << std::endl;
in each iteration and see what happens.
Upvotes: 2