What is a `std::set<int,int>::iterator`?

Viewed 389

I came across the following strange looking code snippet online (simplified).

#include <iostream>
#include <set>

using namespace std;

int main() {
    set<int> myset{1, 2, 3, 4, 5};
    set<int, int>::iterator it = myset.begin();
    cout << *it << endl;
    return 0;
}

I just verified this compiles and runs. (it prints 1 when executed)

I don't understand the iterator type definition.

Defining myset as set<int, int> myset; is invalid as the second optional template parameter of the set type declaration must be a comparator supporting bool operator()(int& const lhs, int& const rhs) const.

But why does the iterator definition not fail? Shouldn't it's underlying container have the same type as the target container ?

1 Answers

You are correct that the second template argument is invalid. That violates the container's preconditions, making the whole thing have undefined behavior. But there are several things to unpack here in general, so we could reason about it somewhat. The key points are these:

  1. An invalid template argument has to be used by the instantiation somehow to trigger a failure. And it has to be used in a place that's instantiated along with the class definition. Not the entirety of the class is always instantiated. A famous example is member function bodies. Those are instantiated only as needed, when actually called.

  2. The iterator type may be an alias. Furthermore, it may be an alias to a type that several different set specializations share. In such a case, it's not inconceivable that ::iterator only depends on the first template parameter. Which means that the type you created may be the same type returned by the other begin.

But ultimately, this is an ill-formed program. Mixing iterators from different containers is undefined in itself, but you also have a precondition violation that precedes that. All in all, it's not something worth stressing about, since such code should not appear anywhere except in intellectual exercises.

Related