0

I faced a problem of overloading the ->() operator while implementing the Iterator class. How should this operator be overloaded?

class iterator
{
private:
    pair<Key_t, Val_t> p;

public:
    iterator()
    {

    }

    iterator(const iterator &i)
    {
        p = i.p;
    }

    iterator(Key_t key, Val_t v)
    {
        p = make_pair(key,v);
    }

    pair<const Key_t,Val_t>& operator *() const
    {
        return p;
    }

    iterator& operator = (const iterator &iter)
    {
        this->p = iter;
        return *this;
    }
};

tried this way unsuccessfully

&(pair<const Key_t,Val_t>&) operator ->() const
    {
        return &(**this);
    }
Dmitry S.
  • 23
  • 3
  • 8

1 Answers1

0

This whole approach looks wrong.

An iterator isn't supposed to contain a value, it's supposed to contain at least

  • The information necessary to locate a value inside the container.
  • Information necessary to traverse to the next element within the container.

By storing a value inside the iterator, you cause unnecessary copies and lose the ability to update the container (change the value, remove the element from the container, etc).

For example, an iterator for a std::vector-like container might store a handle to the container and the index (offset) to the current item.

The only time an iterator would have a value itself is when you're implementing a generator that isn't actually associated with a container.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720