How to order set <pair <unsigned int, double >> with the second value of the pair?

As the name says, I built a set of pair values ​​that I need to order by double value (second):

set<pair<unsigned int, double> > s

+4
source share
4 answers

You should use a comparator:

 struct Cmp { bool operator ()(const pair<unsigned int, double> &a, const pair<unsigned int, double> &b) { return a.second < b.second; } }; 

and then you can define your set as follows:

 set <pair<unsigned int, double>, Cmp> your_set; 
+10
source

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
source

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
source

You can use the card instead of dialing. With doulbe key and unsigned int value. std :: Map <double, unsigned int> s;

0
source

Source: https://habr.com/ru/post/1403251/


All Articles