I was trying to insert few values from a vector to that same vector object but it seems to have erred:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vec;
for(int i=0;i<9;i++)
{
vec.push_back(i+1);
}
vec.insert(vec.begin(),vec.begin()+2,vec.end()-4); //PROBLEM
vector<int>::iterator ivec=vec.begin();
while(ivec!=vec.end())
{
cout<<*ivec<<' ';
++ivec;
}
cout<<endl;
return 0;
}
I am expecting that elements from vec.begin()+2
i.e. 3 to element vec.end()-4
i.e. 6 are inserted in the vector. But the output is:
3 1 2 1 2 3 4 5 6 7 8 9
Compiler is g++ 4.1.2
. Where am I wrong in this?
The problem is that when you start inserting elements you invalidate any existing iterators to that vector, including the iterators that specify the range you are trying to insert. Simple solution is to copy the slice of the vector you want to insert first.
vector<int> tmp(vec.begin() + 2, vec.end() - 4);
vec.insert(vec.begin(), tmp.begin(), tmp.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With