0

I have pushed 1 element in vector and popped it in this program:

 `
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main()
{
vector<int> ivec;
ivec.push_back(9);
vector<int>::iterator l=ivec.end();
cout<<"Size before popping = "<<ivec.size()<<"|| last element before deletion is = "<<*--l<<endl<<endl;
ivec.pop_back();
cout<<"size after popping = "<<ivec.size()<<"|| after deletion, last element is = "<<*l<<endl;
return 0;
}

Even after popping the element, iterator is outputting 9. Why is it still pointing to the deleted value? Doesn't this behavior make iterators untrustworthy?

Is it because the iterator might be pointing to the memory which was previously the part of the vector? Shouldn't the iterator sync it with the changed size?

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)

  • 1
    *Doesn't this behavior make iterators untrustworthy?* No it doesn't. By modifying the vector you invalidate the iterator. It is your responsibility to watch for that. – NathanOliver Mar 16 '17 at 22:29
  • You are invoking Undefined Behaviour. – Richard Critten Mar 16 '17 at 22:29
  • Because you have a bug in your code, and some bugs in C++ lead to strange observed behaviour. – juanchopanza Mar 16 '17 at 22:29
  • @NathanOliver "invalidated"?? You mean now the iterator becomes useless after modification? –  Mar 16 '17 at 22:31
  • @infinite see this: http://stackoverflow.com/questions/6438086/iterator-invalidation-rules – NathanOliver Mar 16 '17 at 22:32
  • 1
    @infinite the **iterator** is invalidated, but the **memory** it was pointing at may still be allocated. Popping an element does not reallocate the vector's capacity, but it may shift remaining data around. – Remy Lebeau Mar 16 '17 at 22:39
  • This isn't the problem, but don't use `std::endl` unless you need the extra stuff that it does. `'\n'` ends a line. – Pete Becker Mar 16 '17 at 22:51

0 Answers0