问题描述
我正在使用标准的 list
容器创建一个 Set 类。当我声明列表迭代器 iter
时,出现错误:
C3861 'iter':标识符未找到
我发现了一些其他人以这种方式声明列表迭代器的例子,但我可能对迭代器有一些误解。
#include <list>
#include <iterator>
using namespace std;
template <typename T>
class Set
{
private:
list<T> the_set;
list<T>::iterator iter;
public:
Set() {}
virtual ~Set() {}
void insert(const T& item) {
bool item_found = false;
for (iter = the_set.begin(); iter != the_set.end(); ++iter) {
if (*iter == item) item_found = true;
}
if (!item_found) {
iter = the_set.begin();
while (item > *iter) {
++iter;
}
the_set.list::insert(iter,item);
}
}
}
list<T>::iterator iter;
解决方法
编译器被那行代码弄糊涂了,因为它不知道 list<T>
是什么,然后才真正用一些 T
专门化类。
更正式地说,list<T>::iterator
是一个 dependent name。
解决方案是以 typename
关键字的形式添加一个提示,以指定该构造毕竟将引用某种类型。
即这应该会有所帮助:
typename list<T>::iterator iter;