我正在尝试使用boost :: bind,boost :: lambda库以及它们如何与STL算法一起使用。假设我有int-string对的向量,它按int键排序。然后在保持向量排序的同时插入新对的位置可以如下找到:
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)
现在我想用函数对象替换operator<
(在此示例中为std::less<int>
类型):
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
答案 0 :(得分:3)
您遗失的是另一个bind
(以及pair
上的模板参数):
std::lower_bound(entries.begin(), entries.end(), k,
boost::bind(comparator,
boost::bind(&std::pair<int, string>::first, _1),
k))
您不必在原始代码中的less-than运算符上执行此操作,因为Boost.Bind为知道如何处理boost::bind
的返回类型的运算符提供重载。