Mayank Jain Mayank Jain - 1 month ago 20
C++ Question

Custom iterator operator overloading

I am trying to implement

->
operator of a custom Iterator. However I am not getting how to define them precisely.

My Iterator class and MapNode are defined like:

template <typename Key_T,typename Mapped_T>
class Map<Key_T,Mapped_T>::Iterator
{
MapNode<Key_T,Mapped_T>* curr;
}

template <typename Key_T,typename Mapped_T>
class MapNode
{
Key_T key;
Mapped_T value;
MapNode *up,*down,*prev,*next;
friend class Map<Key_T,Mapped_T>;
};


Now I want to overload operator->, but the problem is I am not exactly getting how to return pointer of pair of key and value where iterator is currently pointing:

My current implementation is :

template <typename Key_T,typename Mapped_T>
std::pair<const Key_T, Mapped_T>*
Map<Key_T,Mapped_T>::Iterator::operator->() const
{
const Key_T currKey = (this->curr)->key;
const Mapped_T currVal = (this->curr)->value;

ValueType* vt = new ValueType(std::make_pair(currKey,currVal));

return vt;
}


But I am afraid that this will cause memory leaks as the ValueType pointer memory won't be deallocated ever.

Can someone guide me on how can this be done correctly?

Please help.

[ValueType is defined as std::pair<const Key_T, Mapped_T>]

Answer

I would start by storing the values in the MapNode in an std::pair:

template <typename Key_T,typename Mapped_T>
class MapNode
{
    std::pair<Key_T, Mapped_T> value;
    MapNode *up,*down,*prev,*next;
    friend class Map<Key_T,Mapped_T>;
};

Then the iterator can just return the address of that pair.

template <typename Key_T,typename Mapped_T>
std::pair<const Key_T, Mapped_T> *
Map<Key_T,Mapped_T>::Iterator::operator->() const
{
    using ptr = std::pair<const Key_T, Mapped_T> *;
    return (ptr)(&(curr->value));
}

The cast is a little ugly, but that's why you encapsulate it inside a piece of code you rarely have to look at.