Search code examples
c++iterator

Can I use std::next on user defined class


If I have a user-defined class :

class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;

Can I use std::next on objects of MyColl If yes, then what needs to be done


Solution

  • // How to implement a forward iterator for your collection class
    
    template <typename T>
    class MyCollection
    {
    public:
    
      struct MyCollectionIterator
      {
        // These five typedefs tell other things about your iterator 
        
        using iterator_category = std::forward_iterator_tag;
        using value_type        = T;
        using difference_type   = std::ptrdiff_t;
        using pointer           = T*;
        using reference         = T&;
        
        explicit MyCollectionIterator( ... ) ... {}
        
        // These five methods implement the minimum required behavior of a forward iterator
        
        reference  operator *  () const {...}
        iterator & operator ++ ()       {...}
        iterator   operator ++ (int)    {...}
        
        bool operator == ( iterator that ) {...}
        bool operator != ( iterator that ) {...}
      };
      
      MyCollectionIterator begin() { return MyCollectionIterator(...); }
      MyCollectionIterator end()   { return MyCollectionIterator(...); }
    };
    

    There are other iterator types beyond a forward iterator. If possible, you should implement the most capable iterator type you can: if not random access, then bidirectional, and if not bidirectional, then forward.

    Iterators have been an increasingly frightening thing to look at in C++ (see docs here), but the basic idea is simply a class that knows how to pretend to be a pointer sufficient to access your collection’s data. To do that it must provide certain kinds of information and capabilities.

    That little table of iterator types in the linked docs will help you when adding the required functionality to your iterator class.