How to implement an STL-style iterator and avoid c

2019-01-01 06:21发布

I made a collection for which I want to provide an STL-style, random-access iterator. I was searching around for an example implementation of an iterator but I didn't find any. I know about the need for const overloads of [] and * operators. What are the requirements for an iterator to be "STL-style" and what are some other pitfalls to avoid (if any)?

Additional context: This is for a library and I don't want to introduce any dependency on it unless I really need to. I write my own collection to be able to provide binary compatibility between C++03 and C++11 with the same compiler (so no STL which would probably break).

7条回答
只若初见
2楼-- · 2019-01-01 06:52

First of all you can look here for a list of the various operations the individual iterator types need to support.

Next, when you have made your iterator class you need to either specialize std::iterator_traits for it and provide some neccessary typedefs (like iterator category or value type) or alternatively derive it from std::iterator, which defines the needed typedefs for you and can therefore be used with the default std::iterator_traits.

disclaimer: I know some people don't like cplusplus.com that much, but they provide some really useful information on this.

查看更多
登录 后发表回答