Defining iterator of my own container

前端 未结 3 1978
时光说笑
时光说笑 2021-01-02 02:47

I am confused with some concepts about defining my own iterator:

From this: http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterator-define.html, which

3条回答
  •  长发绾君心
    2021-01-02 03:18

    Although @templattypedef's answer is accurate, perhaps I can clarify the situation a little bit.

    An iterator is typically defined as a nested class inside the container. std::iterator is typically used as a base class to make it easier for you to define your iterator class. You never really have to use std::iterator -- it's just there to make the job a bit easier and (especially) reduce the amount of code you need to type. In fact, std::iterator is officially deprecated, so using it is discouraged. It might someday be removed from the standard (though I don't know of any concrete date when it's likely to be removed).

    Oh, and for reasons that have no bearing on the question at hand, it's sometimes preferable for an iterator to be defined outside the container class being iterated. When the iterator class definition is nested in the container definition, the iterator depends on all the template parameters of the surrounding class. That's rarely necessary or desirable though. For example, two vectors with different allocators can still normally have the same iterator type--changing the allocator doesn't change iteration.

提交回复
热议问题