如何为列表编写for循环?

use*_*486 -3 c++ for-loop function list

我目前正在尝试为列表编写循环.我的代码是:

template<typename T>
void Bubblesorting(list<T> & mylist)
{ 
    typename T::const_iterator it1;
    typename T::const_iterator it2;
    for(it1=mylist.begin();it1!=mylist.end();it1++)
        for(it2=mylist.begin();it2!=mylist.end()-(it1-begin());it2++)
            if((*(std::next(it2,1))<*it2)
                swap((*(std::next(it2,1)),*it2);
        cout << *it2 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

编译失败:

 error C2958: the left parenthesis '(' was not matched correctly
Run Code Online (Sandbox Code Playgroud)

你能帮我检一下究竟是什么问题吗?我如何为列表元素编写for循环?

Lig*_*ica 6

功能体{}周围有它们.事实上,你还需要在你的外环体周围.

您的迭代器类型也是错误的,因为T是列表类型,而不是列表的元素类型.此外,它需要是a const_iterator,因为您通过const引用传递列表.

typename T::const_iterator it1;
Run Code Online (Sandbox Code Playgroud)

最后,既不(it2)+1mylist.end()-it1也不可能,因为列表不适应随机访问.您可以std::advance和朋友一起伪造它,但由于遍历列表并非易事(由于数据结构的设计),因此很难理解.

一般来说,我会重新审视整个功能的概念.为什么不用std::list::sort

我建议从这些书籍中挑选.

  • 我很惭愧地说我错过了那个>.> (2认同)