1

I have something like this :

vector<int> tmp={1,4,6,10,6};
vector<int>::iterator it1=tmp.begin()+1;
vector<int>::iterator it2=tmp.begin()+3;

// printing before insertion
cout<<*it1<<" "<<*it2<<endl;

tmp.insert(tmp.begin()+2, 200 );

//printing after insertion
cout<<*it1<<" "<<*it2<<endl;

I get some output like this :

4 10
0 10

Can someone help me understanding what wrong is happening here ?

danish sodhi
  • 1,301
  • 3
  • 14
  • 27
  • 1
    Related: https://stackoverflow.com/questions/6438086/iterator-invalidation-rules – Jeremy Friesner Oct 16 '17 at 23:54
  • I followed it before posting. I states that "all iterators and references before the point of insertion are unaffected" .... So " it1 " here points to element before the insertion point, so why is it affected ? Why has its value become 0 even if it is before insertion point ? – danish sodhi Oct 16 '17 at 23:55
  • "... unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)" – Jeremy Friesner Oct 16 '17 at 23:56
  • So if I am inserting an element, doesnt that mean container size will always increase ? Under what conditions container size remain same ? – danish sodhi Oct 16 '17 at 23:57
  • The number of items in the container will increase; the capacity of the container (which is a different thing) will increase only if the container doesn't currently have enough allocated storage to hold the additional items, and has to reallocate a new (larger) internal array in order to accomodate them. – Jeremy Friesner Oct 16 '17 at 23:58
  • @JeremyFriesner: Thanks for the reference. So that explains why it1 is invalidated, but why was it2 unaffected in this example? – ScottK Oct 16 '17 at 23:58
  • 2
    @ScottK: undefined behavior. If the vector has to reallocate the internal array, ALL existing iterators are invalidated. To make the example work correctly, use indexes instead of iterators – Remy Lebeau Oct 16 '17 at 23:59
  • 2
    @ScottK I don't think it2 was unaffected; I think it *seems* unaffected because one of the (more nefarious) possible outcomes of undefined behavior is that things can *seem* to work the way you would expect in certain scenarios. In particular, I suspect that it2 is pointing to free memory that (by dumb luck) hasn't been overwritten with new data yet. – Jeremy Friesner Oct 16 '17 at 23:59
  • "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)" . How will I (as a coder)know that new container size is becoming greater than capacity. Should I assume that its always unsafe to use iterators after insertion ? – danish sodhi Oct 17 '17 at 00:04
  • I recommend not modifying a container during a traversal of that container. That said, if you want to know the vector's current capacity, you can find out by calling its capacity() method. – Jeremy Friesner Oct 17 '17 at 03:43

0 Answers0