使用lambda的c ++ 11排序列表

pun*_*sta 5 c++ sorting lambda list c++11

在研究lambda期间,我希望list按第二个元素(int)排序.这个使用的代码.

#include <iostream>
#include <algorithm>
#include <list>

using namespace std;
int main()
{
list<pair <string, int>> s = {{"two", 2}, {"one", 1}, {"three", 3}};
sort(s.begin(), s.end(), [](pair<string,int> a, pair<string,int> b) -> bool
                            {
                            return (a.second) > (b.second);
                            }
);

for_each(s.begin(),s.end(),[](pair<string,int> a)
{
    cout << a.first << " " << a.second << endl;
});
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

c:\qt\qt5.2.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_algo.h:5513: error: no match for 'operator-' (operand types are 'std::_List_iterator<std::pair<std::basic_string<char>, int> >' and 'std::_List_iterator<std::pair<std::basic_string<char>, int> >')
     std::__lg(__last - __first) * 2, __comp);
                  ^

c:\qt\qt5.2.0\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_algo.h:2245: ??????: 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<std::pair<std::basic_string<char>, int> >; _Compare = main()::__lambda0]', declared using local type 'main()::__lambda0', is used but never defined [-fpermissive]
     __final_insertion_sort(_RandomAccessIterator __first,
     ^
Run Code Online (Sandbox Code Playgroud)

怎么了?

Vla*_*cow 9

您不能使用std::sort顺序容器,例如,std::list或者std::forward_list因为它们没有标准算法所需的随机访问迭代器std::sort.由于这个原因,两个容器都有自己的成员函数排序.

在您的情况下,代码将看起来如下:

#include <iostream>
#include <list>
#include <string>

using namespace std;

int main()
{
   list<pair <string, int>> s = {{"two", 2}, {"one", 1}, {"three", 3}};
   s.sort( []( const pair<string,int> &a, const pair<string,int> &b ) { return a.second > b.second; } );

for ( const auto &p : s )
{
    cout << p.first << " " << p.second << endl;
}

}
Run Code Online (Sandbox Code Playgroud)

考虑到您需要包含头文件,<string>否则您的程序将不会与其他编译器一起编译.


jua*_*nza 7

std::sort需要随机访问迭代器,它std::list没有.但你可以std::list::sort改用.

s.sort([](const pair<string,int>& a, const pair<string,int>& b)
       {
         return (a.second) > (b.second);
       });
Run Code Online (Sandbox Code Playgroud)

我已经创建了谓词const引用的参数,因为不需要复制它们,这样做可能会产生一些不必要的开销.