[英]How do I create a set with std::pair thats sorted based on the ::second pair member using bind
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 但想知道是否可以用boost :: bind完成
How about the following one. 下面怎么样? I'm using boost::function to 'erase' the actual type of the comparator.
我正在使用boost :: function来“擦除”比较器的实际类型。 The comparator is created using boost:bind itself.
使用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;
}
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. 问题是 - 除非您将代码编写为模板或使用C ++ 0x功能 - 您必须命名boost :: bind表达式的类型。 But those types usually have very complicated names.
但这些类型通常具有非常复杂的名称。
Template argument deduction in C++98: 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: 使用C ++ 0x中的auto和decltype:
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) (另)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.