1

I thought vector::end() equals to any iterator beyond the vector size, but recently I realized that end() + 1 != end().

I experimented further with the following code compiled by g++:

int main() {
    vector<int> v(10);

    cout << (v.end() - v.begin()) << endl;     // 10
    cout << (v.end() + 1 - v.begin()) << endl; // 11
    cout << (v.end() + 1 == v.end()) << endl;  // false
    return 0;
}

It is like the iterator actually holds an array index under the hood.

So my question is: for vector, is this well-defined or compiler-dependent?

Antares
  • 213
  • 1
  • 8
  • `end()` already points one beyond the last element. – πάντα ῥεῖ Sep 26 '21 at 07:41
  • 6
    Incrementing the `end()` iterator causes undefined behavior. – HolyBlackCat Sep 26 '21 at 07:42
  • @asmmo You're confusing `end()` with an iterator to the last element, it seems. `end()` is already one element past the end of the container, dereferencing `end()` itself is UB. – HolyBlackCat Sep 26 '21 at 07:46
  • 2
    Incrementing an end iterator (e.g. `++end_iterator`) or adding `1` to an end iterator (e.g. `v.end() + 1` or (equivalently) advancing an end iterator by `1` (e.g. `std::advance(end_iterator, 1)`) all give undefined behaviour. So both the second and third lines aren't guaranteed to produce the same result or output. – Peter Sep 26 '21 at 07:53
  • Thanks guys. By using **incrementing** as a keyword, I found this answer: https://stackoverflow.com/a/1057788/3235047 . The conclusion is: incrementing end() is UB. – Antares Sep 26 '21 at 07:57
  • Peter, BlackCat Thank u. – asmmo Sep 26 '21 at 08:04

0 Answers0