0

I cannot figure why I'm getting an error when running the following simple program

#include <iostream>
#include <vector>

int main(int argc, char** argv) {
    std::vector<int> v{ 1,2,3,4,5 };
    std::vector<int>::iterator it1 = v.end();
    auto it_tmp = v.insert(v.end(), 6);
    std::vector<int>::iterator it2 = v.end();

    std::cout << (it1 == it2) << std::endl;

    return 0;
}

The iterators it1 and it2 are incompatible, so I was wondering what could possible be the issue. Iterators are incompatible if they belong to different containers, I would then assume in my case one of the two gets invalidated or something like that (I've also try to change v.end with v.begin() for both it1 and it2, it doesn't make any difference).

Thank you.

user8469759
  • 2,522
  • 6
  • 26
  • 50

1 Answers1

3

it1 == it2 evaluates false because after this auto it_tmp = v.insert(v.end(), 6);, end iterator changes.

std::vector::insert inserts before the given iterator. Everything before the insertion point remains valid. Everything after it is invalidated. it1 here is invalidated:

std::vector::insert

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

Community
  • 1
  • 1
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93