hl037_
hl037_

Reputation: 3907

Why does not `std::set<T>::end()` compare equal to `std::set<T>::iterator{}`?

Compile this code :

#include <set>
#include <iostream>

int main(int argc, char * argv[]){
  std::set<int> test;

  std::cout << (test.end() == std::set<int>::iterator{}) << std::endl;
  std::cout << (test.begin() == std::set<int>::iterator{}) << std::endl;
  std::cout << (test.begin() == test.end()) << std::endl;

  return 0;
}

It outputs (tested on gcc 11.1 and clang 12.0.0):

0
0
1

...However, if I refer to https://timsong-cpp.github.io/cppwp/n4659/iterators#forward.iterators-2

The domain of == for forward iterators is that of iterators over the same underlying sequence. However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type. [ Note: Value-initialized iterators behave as if they refer past the end of the same empty sequence.  — end note ]

...Then std::set<int>::iterator{} is what I understand to be "value-initialized" (note that I get the same result using a temporary variable), and I would expect the output to be :

1
1
1

What am I missing ?

Upvotes: 1

Views: 220

Answers (2)

Jeff Garrett
Jeff Garrett

Reputation: 7508

The domain of == for forward iterators is that of iterators over the same underlying sequence.

So... one can compare iterators from the same sequence with ==.

However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.

So... one can compare two value-initialized iterators of the same type with ==.

Note: Value-initialized iterators behave as if they refer past the end of the same empty sequence.

Notes are not normative, but this is describing that there is some empty sequence hidden from you, and the value-initialized iterators act as if they refer to the past the end iterator of this sequence.

This is saying that it is as if the standard library instantiated for itself a std::set<int> and a value-initialized iterator referred to the .end() of that.

The note is consistent with the above. If value-initialized iterators act as if they all point into the same sequence, at the same point, they will be comparable and compare equal.

Upvotes: 4

Mooing Duck
Mooing Duck

Reputation: 66961

It's undefined behavior to compare value-initialized iterators to iterators from a sequence.

"Value-initialized iterators behave as if they refer past the end of the same empty sequence" indicates that they cannot be dereferenced or advanced.

Upvotes: 3

Related Questions