"identifier not found" 尝试声明列表迭代器时

"identifier not found" when trying to declare a list iterator

我正在使用标准 list 容器创建集合 class。当我声明列表迭代器 iter 时,出现错误:

C3861 'iter':identifier not found

我发现了一些其他人以这种方式声明列表迭代器的例子,但我可能对迭代器有一些误解。

#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;

编译器对该行感到困惑,因为在实际将 class 专门化为一些 T.

之前,它不知道 list<T> 会是什么

更正式地说,list<T>::iteratordependent name

解决方案是以 typename 关键字的形式添加一个提示,以指定构造毕竟将引用某种类型。

即这应该有所帮助:

    typename list<T>::iterator iter;