Reputation: 6018
vector <vector <int>> frameVecs(4);
vector <int> t1 = getPeaks (vec1);
vector <int> t2 = getPeaks (vec2);
vector <int> t3 = getPeaks (vec3);
vector <int> t4 = getPeaks (vec4);
frameVecs[0].reserve(t1.size());
frameVecs[1].reserve(t2.size());
frameVecs[2].reserve(t3.size());
frameVecs[3].reserve(t4.size());
frameVecs.push_back (t1);
frameVecs.push_back (t2);
frameVecs.push_back (t3);
frameVecs.push_back (t4);
I always get subscript out of range
error during the pushback part of the snippet.
Just two days back I was with this code that does the same thing:
vector <vector <int>> frameVecs;
frameVecs.push_back (getPeaks (vec1));
frameVecs.push_back (getPeaks (vec2));
frameVecs.push_back (getPeaks (vec3));
frameVecs.push_back (getPeaks (vec4));
And this was running just fine for the last 2 months .. and suddenly I started getting subscript out of range
error in the pushback part and hence I had to change thsi particular part into the one above it, and still I am getting this error.
I mean, are vectors
so uncertain in their behavior ?
PS: getPeaks() returns an int
vector!
Upvotes: 0
Views: 103
Reputation: 8027
Excelcius's answer is good, but here's another way to do what I think you are trying to do.
vector <vector <int>> frameVecs(4);
frameVecs[0] = getPeaks (vec1);
frameVecs[1] = getPeaks (vec2);
frameVecs[2] = getPeaks (vec3);
frameVecs[3] = getPeaks (vec4);
The main thing here is that this code is simpler than your code. When simple things get as complicated as your code it's a pretty clear indication that something is wrong.
Main misunderstanding seems to be that either you set the size of a vector in the constructor or you dynamically increase the size using push_back, rarely do you want to do both.
Upvotes: 0
Reputation: 1690
I think push_back
doesn't do what you think it does.
vector <vector <int>> frameVecs(4);
Passing 4 to the vector on construction already creates 4 empty int
-vectors. If you push_back
the 4 vectors t1
, t2
, t3
and t4
you add another 4 vectors to frameVecs
, so you actually have 8 entries in frameVecs
. Maybe removing (4)
and just writing:
vector <vector <int>> frameVecs;
will solve the problem.
If you now try to access frameVecs[0][0]
for example (although not shown in your example) you get an error.
After the 4th push_back
frameVecs
looks like this:
frameVecs[0] // empty
frameVecs[1] // empty
frameVecs[2] // empty
frameVecs[3] // empty
frameVecs[4] // contains t1
frameVecs[5] // contains t2
frameVecs[6] // contains t3
frameVecs[7] // contains t4
Calling reserve
is also unnecessary in this example.
Upvotes: 4