what is the type of an iterator in STL?

 ̄綄美尐妖づ 提交于 2019-12-25 08:29:55

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10364050/what-is-the-type-of-an-iterator-in-stl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!