Vanya Ryanichev
Vanya Ryanichev

Reputation: 115

How exactly iterators are being compared?

#include <iostream>
#include <set>
using namespace std;
int main() {
  set<int> numbers;
  numbers.insert(1);
  auto numbers_find = numbers.find(1);
  auto numbers_end = numbers.end();
  cout<<*numbers_find<<endl;
  cout<<*numbers_end<<endl;
  cout<<(numbers_find==numbers_end?"true":"false")<<endl;
  return 0;
}

In that case output would be

1
1
false

As well as I understand iterators are basically pointers, but only for elements of STL collections. So my question is - what exactly is being compared when we comparing two iterators, I assume this is some kind of equivalent of address that pointer points to. But, according to pointers logic, if two iterators pointing to the same element, then it would make sense if they were equal.

int a = 5;
int *ptr1 = &a;
int *ptr2 = &a;
cout<<((ptr1==ptr2)?"true":"false")<<endl;

Output

true

P.S. Link to code example above https://repl.it/@VanyaRyanichev/FrillyPapayawhipMonitor#main.cpp

Upvotes: 1

Views: 79

Answers (1)

Caleth
Caleth

Reputation: 62576

The end iterator does not point to the last element, it doesn't point to anything. Your program is ill-formed (has undefined behaviour).

C++ expresses sequences as half-open intervals

Upvotes: 4

Related Questions