Invictus
Invictus

Reputation: 4328

what is the type of an iterator in STL?

Every Variable in c++ has some type like in int i , i has a type int . Similarly we have iterators in STL which we declare say something like this

       map<string,int>::iterator it .

What is the type of the it over here ? Is it pointer type or is it a pointer type as we gerally deference iterators to fetch values associated or pointed by those itearors in case of vectors which store int or some other type.? Or the operator * is overloaded for iterators in STL ?

Upvotes: 6

Views: 14666

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137800

24.2.1/1 [iterator.requirements.general] sums it up nicely:

Iterators are a generalization of pointers that allow a C++ program to work with different data structures (containers) in a uniform manner. To be able to construct template algorithms that work correctly and efficiently on different types of data structures, the library formalizes not just the interfaces but also the semantics and complexity assumptions of iterators.

The phrase "generalization of pointers" means that pointers are iterators. std::vector<T>::iterator is allowed to be a typedef T *. However, most iterators achieve the interface by operator overloading. (Note that iterators don't need to belong to containers, either.)

Such language is very typical of the way the C++ standard is written. It describes how things behave, but avoids defining interfaces in terms of base classes. There are various kinds of iterators: input, output, forward, bidirectional, and random-access. Each has a different specification, and although random-access is a strict superset of the bidirectional interface, they are totally unrelated in the C++ type system.

An iterator can be any class with ++ and * overloaded, and a valid specialization of std::iterator_traits. There is a base class std::iterator which works with std::iterator_traits to define the necessary interface. It is a good case study in C++ generic programming and traits classes.

Upvotes: 6

NPE
NPE

Reputation: 500307

What is the type of the it?

The type of it is map<string,int>::iterator, which is a class with a bunch of operators overloaded.

For some container types, Container::iterator may be a raw pointer type. For map, it has to be a class.

Upvotes: 9

Related Questions