[英]c++11 sorting list using lambda
While practicing the use of lambdas, I wrote this program which is supposed to sort a list
of pair
s by their second element (an int
).在练习 lambda 的使用时,我编写了这个程序,该程序应该按pair
s 的第二个元素(一个int
) pair
它们的list
进行排序。
#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; }); }
I get those errors, though:不过,我收到了这些错误:
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,
^
What is wrong with my code?我的代码有什么问题?
You may not use std::sort
with sequential containers such as std::list
or std::forward_list
because they have no random access iterator that is required by the standard algorithm std::sort
.您不能将std::sort
与诸如std::list
或std::forward_list
std::sort
的顺序容器一起使用,因为它们没有标准算法std::sort
所需的随机访问迭代器。 By this reason the both containers have their own member functions sort.由于这个原因,两个容器都有自己的成员函数 sort。
In you case the code will look the following way:在您的情况下,代码将如下所示:
#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;
}
}
Take into account that you need to include header <string>
otherwise your program will not be compiled with other compilers.考虑到您需要包含头文件<string>
否则您的程序将不会被其他编译器编译。
std::sort
requires random access iterators, which std::list
does not have. std::sort
需要随机访问迭代器,而std::list
没有。 But you can use std::list::sort
instead.但是您可以改用std::list::sort
。
s.sort([](const pair<string,int>& a, const pair<string,int>& b)
{
return (a.second) > (b.second);
});
where I have made the parameters of the predicate const
references, since there is no need to copy them, and doing so might incur some unnecessary overhead.在那里我制作了谓词const
引用的参数,因为不需要复制它们,这样做可能会导致一些不必要的开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.