Writing my own implementation of stl-like Iterator in C++

前端 未结 2 641
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 01:14

I\'m currently trying to understand the intrinsics of iterators in various languages i.e. the way they are implemented.

For example, there is the following class ex

2条回答
  •  一整个雨季
    2021-01-02 01:50

    The C++ standard library does not use polymorphism and inheritance in its implementation of iterators; instead, it uses C++ template metaprogramming and the notion (but not formal syntax*) of "concepts".

    Essentially, it will work if the interface for your iterator class adheres to some set of requirements. This set of requirements is called a "concept". There are several different iterator concepts (see this page for a list of all of them), and they are hierarchical. The basics of creating a compatible C++ iterator is to make your interface conform to the concept. For a simple iterator that goes only in the forward direction, this would require:

    • A typedef value_type for the value that results from dereferencing your iterator.
    • A typedef reference_type, which is the reference type for the corresponding value type.
    • A typedef pointer, which is a pointer type for the corresponding value type.
    • A typedef iterator_category, which needs to be one of input_iterator_tag, forward_iterator_tag, bidirectional_iterator_tag, or random_access_iterator_tag, depending on your traversal mechanism.
    • A typedef difference_type indicating the result of subtracting two different iterators.
    • A const value_type& operator*()const function for dereferencing the iterator.
    • A value_type& operator*() function if your iterator can be used to manipulate the value.
    • Increment (operator++() and operator++(int) functions) for seeking forward.
    • A difference function: difference_type operator-(const type_of_iterator&)

    If you choose one of the more advanced iterator categories, you may also need to specify a decrement and plus operator in order to be able to seek backwards or to seek an arbitrary distance.

    *The C++ standard library uses concepts so frequently in an informal way, that the C++ standards commitee sought to introduce a formal mechanism of declaring them in C++ (currently they exist only in documentation of the standard library, and not in any explicit code). However, persistent disagreements on the proposal led to it being scrapped for C++0x, although it will likely be reconsidered for the standard after that.

提交回复
热议问题