Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector insert within the same object

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?

like image 557
Agrudge Amicus Avatar asked Dec 14 '22 11:12

Agrudge Amicus


1 Answers

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());
like image 118
john Avatar answered Jan 12 '23 08:01

john