c++11 sorting list using lambda
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;
}
}
Take into account that you need to include header <string>
otherwise your program will not be compiled with other compilers.
std::sort
requires random access iterators, which std::list
does not have. But you can use std::list::sort
instead.
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.