Do you have to implement multiple iterators in a STL-like class?
I'm quite familiar with the STL and how to use it. My question is...
If I were to implement my own开发者_运维百科 STL container type, how are the internal iterators defined? STL classes tend to have sequential or random-access iterators, const_ versions of these, and stream iterators.
Are these iterators all fully-defined in every STL class, or is there some sort of base class that you inherit from to gain most of the iterator functionality? Does anyone know a good reference for how to implement a class that supports these different kinds of iterators?
Generally, you only have to implement iterator
and const_iterator
.
If reverse iterators are desired, they can be obtained using
instantiations of std::reverse_iterator
. The stream iterators will use
operator>>
and operator<<
; typically, they aren't appropriate for a
container (and none of the standard containers provides them).
Yes, you need two different iterators to be fully stdlib compliant.
You can get most typedefs right with inheriting from std::iterator
but this wont give you any help with the actual implementation.
Boost.Iterator Facade tries to simplify defining your own iterators and the tutorial is quite helpful.
Should you attempt to do it without helpers you should think about what concept your iterator models and then look at the tables in §24 of the C++ standard. They describe all operations you need to support and what the intended semantics are.
精彩评论