c++stliteratorinput-iterator

How to implement "dereference and post-increment" for input iterator in C++?


Requirements for InputIterator include *i++ with an equivalent expression being

value_type x = *i;
++i;
return x;

How can one declare such an operator without implementing the standard post-increment i++ returning a non-void value (which InputIterators are not required to do)?


Solution

  • You may use a proxy for the post increment:

    #include <iostream>
    
    class input_iterator
    {
        private:
        class post_increment_proxy
        {
            public:
            post_increment_proxy(int value) : value(value) {}
            int operator * () const { return value; }
    
            private:
            int value;
        };
    
        public:
        post_increment_proxy operator ++ (int) {
            post_increment_proxy result{value};
            ++value;
            return result;
        }
    
        private:
        int value = 0;
    };
    
    
    int main() {
        input_iterator i;
        std::cout << *i++ << '\n';
        std::cout << *i++ << '\n';
        std::cout << *i++ << '\n';
    }