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>]