【发布时间】:2016-01-14 15:07:26
【问题描述】:
我想通过链表实现一个通用地图。 我一直在尝试重载 ++ 运算符以在列表中移动迭代器,但使用 new 运算符时遇到问题。
template <class KeyType, class ValueType, class CompareFunction = std::less<KeyType> >
class MtmMap {
public:
class Node{
public:
const Pair* data;
Node* next;
Node()
: data(NULL),next(NULL){}
Node(const Pair pair){
data=new Pair(pair);
data=&pair;
next=NULL;
}
};
Node* iterator;
// ...
};
这里是重载:
Node* operator++(){
iterator=iterator->next;
return iterator;
}
我想在 mtmMap 的另一个方法中使用 ++ 运算符:
void insert(const Pair pair){
for(begin();iterator->next->data;this++){
}
但我收到以下错误:
“需要作为增量操作数的左值”
“只读位置的增量”
【问题讨论】:
-
请修正压痕并平衡大括号。另外,请澄清您要做什么。在 C++ 中,“迭代器”指的是一种数据类型,但您显然在容器类中创建了一个名为
iterator的成员变量。 -
在 STL 帮派建立更好的方法之前,将迭代状态“混入”正在迭代的集合中是相当普遍的。从标准库中寻找灵感。
-
另外,
data=&pair;会给你留下一个无效的指针,因为pair是一个函数参数。这也是内存泄漏。
标签: c++ operator-overloading increment