Implementing custom iterators in C++11

后端 未结 1 828
野的像风
野的像风 2020-12-29 17:32

I am reading a book, and I started the Templates chapter. I have already read the chapter about iterators. For practicing, I am trying to implement a doubly

相关标签:
1条回答
  • 2020-12-29 18:09

    If you have a look at an implementation of <iterator>, you'll find something like __normal_iterator, which looks like:

    template<typename I>
    class iter
    {
    protected:
        I i;
    
        using tr = iterator_traits<I>;
    
    public:
        using iterator_type     = I;
        using iterator_category = typename tr::iterator_category;
        using value_type        = typename tr::value_type;
        using difference_type   = typename tr::difference_type;
        using reference         = typename tr::reference;
        using pointer           = typename tr::pointer;
    
        iter() : i(I()) { }
    
        explicit iter(const I& i) : i(i) { }
    
        // Forward iterator requirements
        reference operator*() const { return *i; }
    
        pointer operator->() const { return i; }
    
        iter& operator++() { ++i; return *this; }
    
        iter operator++(int) { return iter(i++); }
    
        // Bidirectional iterator requirements
        iter& operator--() { --i; return *this; }
    
        iter operator--(int) { return iter(i--); }
    
        // Random access iterator requirements
        reference operator[](const difference_type& n) const { return i[n]; }
    
        iter& operator+=(const difference_type& n) { i += n; return *this; }
    
        iter operator+(const difference_type& n) const { return iter(i + n); }
    
        iter& operator-=(const difference_type& n) { i -= n; return *this; }
    
        iter operator-(const difference_type& n) const { return iter(i - n); }
    
        const I& base() const { return i; }
    };
    

    This is supposed to work on an ordinary pointer or iterator. All you have to do is use this as a template and adjust to what is needed by your custom container. If T is your value_type, then member functions normally return

    • begin() -> iter<T*>
    • cbegin() -> iter<const T*>
    • rbegin() -> std::reverse_iterator<iter<T*> >
    • crbegin() -> std::reverse_iterator<iter<const T*> >

    However, since you have your node_structure, this is not entirely true and you need to elaborate a bit more.

    0 讨论(0)
提交回复
热议问题