1

I write a piece code with C++ and I used vector.insert() and iterator to inserting values in vector. but I received an error:

Vector iterator not incremental

I can not figure out what is wrong with this code. my guess is ++it, but I can not fix the problem. I would appreciate for any help.

#include <iostream>
#include <vector>
using namespace std;

int main(){

    vector<int>::iterator it;
    vector<int> vec2(4);

    it  = vec2.begin();
    vec2.insert(it, 45);
    ++it;  // error pops here                    
    vec2.insert (it,23);

    for(it = vec2.begin(); it!= vec2.end(); ++it)
            cout << " "<<*it<<endl;
return 0;
}
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
Rommel
  • 1
  • 4

1 Answers1

0

You are pretty close. Your error is that insertion invalidates the iterator, so you need to re-assign it:

it = vec2.insert(it, 45);
++it;                      
it = vec2.insert (it,23);

Demo.

Your program prints 45 23 0 0 0 0. The trailing zeros come from the initial set-up of the vector of four values.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523