C++:如何使用 std::less与 boost::bind 和 boost::lambda 一起吗?

发布于 2024-08-12 00:30:49 字数 866 浏览 2 评论 0原文

我正在尝试学习 boost::bind、boost::lambda 库以及如何将它们与 STL 算法一起使用。假设我有按 int 键排序的 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)

现在我想用函数对象(类型为 std::less替换 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::operator() 不接受 boost::bind 的返回类型。我在这里缺少什么? TIA

I am trying to lean boost::bind, boost::lambda libraries and how they can be used with STL algorithms. Suppose I have vector of int-string pairs which is sorted by int key. Then a place to insert a new pair while keeping the vector sorted can be found as follows:

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)

Now I would like to replace operator< with a function object (of type std::less<int> in this example):

std::less<int> comparator;

How do I change the code above so it works? I cannot just do

std::lower_bound (entries.begin(), entries.end(), k, 
                  comparator (boost::bind (&std::pair<int, string>::first, _1), k))

because std::less<int>::operator() does not accept whatever is the return type of boost::bind. What am I missing here? TIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

街角迷惘 2024-08-19 00:30:49

您所缺少的只是另一个 bind (以及 pair 上的模板参数):

std::lower_bound(entries.begin(), entries.end(), k, 
                 boost::bind(comparator,
                             boost::bind(&std::pair<int, string>::first, _1),
                             k))

您不必在原始代码中的小于运算符上执行此操作,因为Boost.Bind 为该运算符提供了重载,该重载知道如何处理 boost::bind 的返回类型。

All you're missing is another bind (and the template parameters on pair):

std::lower_bound(entries.begin(), entries.end(), k, 
                 boost::bind(comparator,
                             boost::bind(&std::pair<int, string>::first, _1),
                             k))

You don't have to do that on the less-than operator in your original code because Boost.Bind provides overloads for that operator that know how to handle the return type of boost::bind.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文