C++:如何使用std :: less with boost :: bind和boost :: lambda?
问题描述:
我想倾斜boost :: bind,boost :: lambda库以及它们如何与STL算法一起使用。假设我有一个由int键排序的int-string对的向量。然后一个地方插入一对新的,同时保持排序的矢量可以发现如下:C++:如何使用std :: less <int> with boost :: bind和boost :: lambda?
std::vector<std::pair<int, string> > entries;
...
int k = ...;
// Let's ignore std::lower_bound return value for now
std::lower_bound (entries.begin(), entries.end(), k,
boost::bind (&std::pair<int, string>::first, _1) < k)
现在我想与(在本示例std::less<int>
类型的)的函数的对象来取代operator<
:
std::less<int> comparator;
如何更改上面的代码,使其工作?我不能只是做
std::lower_bound (entries.begin(), entries.end(), k,
comparator (boost::bind (&std::pair<int, string>::first, _1), k))
因为std::less<int>::operator()
不接受任何的boost::bind
返回类型。我在这里错过了什么? TIA
答
所有你缺少的是另一个bind
(和pair
模板参数):
std::lower_bound(entries.begin(), entries.end(), k,
boost::bind(comparator,
boost::bind(&std::pair<int, string>::first, _1),
k))
你不必这样做,在低于运营商在原来的代码,因为加速。 Bind为那些知道如何处理boost::bind
返回类型的操作员提供重载。
因此,外部boost :: bind的作用在于让comparator.operator()接受内部boost :: bind产生的任何东西。谢谢! (顺便提一句,缺失的模板参数只是我的编辑错误) – 2009-11-25 06:39:04
我很想这么做。但是当你退后一步时,你意识到你的代码很难阅读。现在,该绑定是C++标准的一部分,您应该注意,只有提升实现重载关系和逻辑运算符。 – 2009-11-25 07:57:54