How to order set <pair <unsigned int, double >> with the second value of the pair?
4 answers
set , in fact, has three parameters, the last two of which are optional. But in your case, you want to use the second parameter, which indicates how the elements will be sorted. By default (ignoring the third parameter), set :
set<typename Key, typename Compare = less<Key>>
You just need to write the appropriate class for the second parameter, for example:
template<typename Pair> class CompareSecond { bool operator()(const Pair& firstPair, const Pair& secondPair) { return firstPair.second < secondPair.second; } } And then you create your set as:
typedef pair<unsigned int, double> MyPair; set<MyPair, CompareSecond<MyPair>> s; +2
In C ++ 11, you probably want to use lambda. Unfortunately, it is not possible to get a lambda type in an invaluable context. Therefore, we need to cheat a little to get the argument:
#include <set> template<typename T, typename Cmp> std::set< T, Cmp > make_set(Cmp cmp) { return std::set<T, Cmp>(cmp); } int main() { auto s = make_set<std::pair<int, int> >( [](const std::pair<int, int>& p1, const std::pair<int, int>& p2) { return p1.second < p2.second; } ); return 0; } make_set is a good functor, but it does not work if you need to specify a dispenser for set .
+1