How do I create a set with std::pair thats sorted based on the ::second pair member using bind

北城余情 提交于 2019-12-22 08:28:55

问题


I know I could 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 it could be done with boost::bind


回答1:


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

  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;
  }



回答2:


The problem is that -- unless you write your code as a template or use C++0x features -- you have to name the type of the boost::bind expression. But those types usually have very complicated names.

Template argument deduction 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(…));
}

As for the actual bind expression, I think it's something like this:

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

(untested)



来源:https://stackoverflow.com/questions/2958226/how-do-i-create-a-set-with-stdpair-thats-sorted-based-on-the-second-pair-mem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!