How to create a set with std :: pair sorted by :: second pair element using bind

I know I can use the following:

template <typename Pair> struct ComparePairThroughSecond : public std::unary_function<Pair, bool> { bool operator ()(const Pair& p1, const Pair& p2) const { return p1.second < p2.second; } }; std::set<std::pair<int, long>, ComparePairThroughSecond> somevar; 

but wondered if this can be done with boost :: bind

+4
source share
2 answers

How about the following. I use boost :: function to erase the actual type of comparator. The comparator is created using boost: bind.

  typedef std::pair<int, int> IntPair; typedef boost::function<bool (const IntPair &, const IntPair &)> Comparator; Comparator c = boost::bind(&IntPair::second, _1) < boost::bind(&IntPair::second, _2); std::set<IntPair, Comparator> s(c); s.insert(IntPair(5,6)); s.insert(IntPair(3,4)); s.insert(IntPair(1,2)); BOOST_FOREACH(IntPair const & p, s) { std::cout << p.second; } 
+3
source

The problem is that - if you do not write your code as a template or use the C ++ 0x functions, you must specify the type of the expression boost :: bind. But these types usually have very complex names.

The output of the template argument in C ++ 98:

 template<class Fun> void main_main(Fun fun) { set<pair<int,long>,Fun> s (fun); … } int main() { main_main(…boost::bind(…)…); } 

With auto and decltype in C ++ 0x:

 int main() { auto fun = …boost::bind(…)…; set<pair<int,long>,decltype(fun)> s (fun); main_main(boost::bind(…)); } 

Regarding the actual binding expression, I think it is something like this:

 typedef std::pair<int,long> pil; boost::bind(&pil::second,_1) < boost::bind(&pil::second,_2) 

(unverified)

0
source

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


All Articles