【问题标题】:Cannot iterate through a Template List C++无法遍历模板列表 C++
【发布时间】:2011-12-19 05:43:02
【问题描述】:

我不熟悉在 C++ 中使用模板,我正在尝试遍历模板列表。

这是我的代码

template <typename T>
void pleaseWork(const list<T>& aList, list<T>& list1, list<T>& list2) 
{
typename list<T>::iterator i;
int n = 0;
for(i = aList.begin(); i != aList.end(); ++i) {
         //Do something crazy
         n++;
}

}

int main()
{
    list<int> lista;
    list<int> list1;
    list<int> list2;
    for (int i = 0; i < 10; i++) {
        lista.push_back(i*2);
    }

    pleaseWork(lista, list1, list2);

return 0; 
}

编译时出现以下错误: 错误:与 _Tp = int, _Alloc = std::allocator' 的 i = ((const std::list&lt;int, std::allocator&lt;int&gt; &gt;*)aList)-&gt;std::list&lt;_Tp, _Alloc&gt;::begin 中的“operator=”不匹配

感谢您的帮助

【问题讨论】:

    标签: c++ list templates iterator


    【解决方案1】:

    aList 是对const 的引用,因此begin() 将返回const_iterator

    如果您的编译器支持,请使用auto

    【讨论】:

      【解决方案2】:

      由于您将pleaseWork 传递给const 列表的引用,因此您需要使用const_iterator 来访问其内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-21
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多