使用 std::list 时编译器错误

Compiler error with using std::list

本文关键字:编译器 错误 list std 使用      更新时间:2023-10-16

我有一个简单的函数来检查一个值是否在列表中:

template <class T>
bool IsinList(list<T> l, T x)
{
    for(list<T>::iterator it=list.begin(); it != list.end(); it++)
    {
        if (*it == x)
            return true;
    }
    return false;
}

我在同一个.cpp文件中使用了该函数,如下所示:

if (!IsinList (words, temp))   
    goodwords.push_back(temp);

但是我收到此错误:

'std::list' : use of class template requires template argument list

我无法弄清楚问题是什么。我检查了以前的问题,但没有帮助。你能向我解释我做错了什么吗?

那里有

错别字:

list.begin() / list.end()

应该是

l.begin() / l.end()

您的变量称为 l ,而不是 list

编辑:

正如马蒂尼奥所指出的,这可能还不够。一些编译器会接受这一点,但由于迭代器依赖于模板参数,因此您可能需要一个类型名:

typename list<T>::iterator it=list.begin()

你打错了字(list vs. l ),并且没有指定list<T>::iteratortypename。此外,您应该通过引用 const 传递list和搜索参数。总而言之,它应该看起来像这样:

template <class T>
bool IsinList(const list<T>& l, const T& x)
{
    typename list<T>::const_iterator first = l.begin(), last = l.end();
    for(; first != last; ++first)
    {
        if (*it == x)
            return true;
    }
    return false;
}

也就是说,仍然不要使用它。改用std::find要好得多

if (std::find(words.begin(), words.end(), temp)==words.end())
{
  goodwords.push_back(temp);
}