使用lambda的c ++ 11排序列表 [英] c++11 sorting list using lambda
问题描述
在练习使用lambda时,我编写了该程序,该程序应该按pair
的list
的第二个元素(int
)进行排序.
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
).
#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,
^
我的代码有什么问题?
推荐答案
您不能将std::sort
与顺序容器(例如std::list
或std::forward_list
)一起使用,因为它们没有标准算法所需的随机访问迭代器std::sort
.因此,两个容器都有自己的成员函数sort.
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
. By this reason the both containers have their own member functions 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;
}
}
请注意,您需要包含标头<string>
,否则您的程序将无法与其他编译器一起编译.
Take into account that you need to include header <string>
otherwise your program will not be compiled with other compilers.
这篇关于使用lambda的c ++ 11排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!