【发布时间】:2017-02-22 21:22:28
【问题描述】:
我正在尝试实现自定义迭代器的-> 运算符。但是我不知道如何精确定义它们。
我的 Iterator 类和 MapNode 定义如下:
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>;
};
现在我想重载 operator->,但问题是我没有完全了解如何返回迭代器当前指向的键和值对的指针:
我目前的实现是:
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;
}
但我担心这会导致内存泄漏,因为 ValueType 指针内存永远不会被释放。
有人可以指导我如何正确完成这项工作吗?
请帮忙。
[ValueType is defined as std::pair<const Key_T, Mapped_T>]
【问题讨论】:
标签: c++ stl iterator std stdmap