Inserting element in vector of vector of type class

I have a vector<class>v1 and vector<vector<class>> v2;
I ask the user how many vectors they need then insert like this

for(int i=0;i<=input;i++){
v2.push_back(v1);
}
This works fine. Now I am trying to insert an element in v1 at index 20.

I tried this and when it gets to that area in the code it crashes. I checked to see if there is room and there is. Any other suggestions?
 
v2[number-1].insert(v1.begin()+location, element);
Last edited on
What does the manual say? http://www.cplusplus.com/reference/vector/vector/insert/

Position in the vector where the new elements are inserted.


What have you?
You are inserting into vector v2[number-1]. That is entirely separate vector from the v1. It might have been created by copy construction from v1, but that is all.

Therefore:
v2[number-1].insert( v2[number-1].begin() + location, element );
1
2
3
for(int i=0; i<=printers; i++)
{    v2.push_back(v1);
}

I see two things wrong with that code.

1) You don't show how you derive printers, but if it is the number of vectors you want to insert, you're going to insert one vector too many. The condition should be i<printers.

2) You're inserting the same vector into v2 each time the loop runs.
Topic archived. No new replies allowed.