iamseiko iamseiko - 1 month ago 5x
C++ Question

Why are Iterators notated as value objects, but referenced as pointers?

In the C++ Standard Map Library, a call to the iteration functions returns an iterator pointer,

std::map<int, int> map;
std::map<int, int>::iterator ite = map.find(1);

But, when the iterator is used, it must be accessed as a pointer variable,

int first = ite->first;
int second = ite->second;

Why is this the case when we are putting the obtained value from the
function into a non-pointer. Shouldn't the correct syntax be:

std::map<int, int>::iterator *pIte = map.find(1)

or if using the original syntax,

int first = ite.first;
int second = ite.second;

since we are obtaining a value, and not a pointer from the function's return value? It is also not clarified in the documentation. Why is this the case?


As @jaggedSpire suggested, iterators are supposed to act like ptrs, having defined the operators *, ->, etc. But the thing is, an iterator isn't an explicit pointer. The syntax you suggested:

std::map<int, int>::iterator *pIte = map.find(1);

Is a pointer to an iterator, not just an iterator. The reason when you wrote:

std::map<int, int>::iterator pIte = map.find(1);

you have to write: ite->first is because operator-> is defined for iterators. This means that iterators are supposed to act like pointers.