Hello, I need help with overloading the operator ++ (prefix and postfix).

Imagine that we have a container and a tree. An iterator is implemented in the tree. And the container uses it as its own.

typedef typename tree::TreeIterator iterator; 

begin in this case looks like this:

 iterator begin() { return strom.begin(); } 

where strom is an object of type tree;

The base part of the iterator looks like this:

 template < class Tree, class Key, class mapped_type > struct BaseTreeIterator { typedef BaseTreeIterator self_type; typedef std::pair<Key, mapped_type> value_type; typedef value_type& reference; typedef value_type* pointer; value_type* currPair; Tree* curr; /** Inequality test operator */ bool operator!=(self_type const & other) const { return this->curr != other.curr; } /** Dereference operator */ bool operator==(self_type const & other) const { return this->curr == other.curr; } const self_type& operator++() { curr = successor(); // point to next node if (curr) *currPair = std::make_pair(curr->key, curr->getValue()); return *this; } self_type& operator=(const self_type& other) { //проверка на самоприсваивание if (this == &other) { return *this; } curr = other.curr; currPair = other.currPair; return *this; }} 

The problem itself is that I need to add an overload to the ++ operator. That he supported these functions

 using mp = lib::PersistentMap<int, int>; using mp_it2 = mp::iterator; mp_it2 tmp1; mp_it2 tmp2 = ++tmp1; // ругается на ++ mp_it2 tmp3 = tmp1++; // ругается на tmp1 mp_it2 tmp4(tmp1++); 

But I can not imagine what to tie this overload. And how to make save postfix values.

I would be grateful for advice and / or example.

  • one
    To describe a postfix operator, add int in brackets: const self_type & operator ++ (int); - Vladimir Gamalyan

1 answer 1

Found on the forum.

  // prefix increment (++it) iterator& operator++() { ++p; return *this; } // postfix increment (it++) iterator operator++(int) { return iterator(p++); }