c++ - 如何在复合类型上使用 Boost.Bind?

标签 c++ boost-bind boost-lambda

我有 std::map<int, std::pair<short, float> > ,我需要找到最小的 short在这张 map 中。如何使用 boost::bindstd::min_element()为了这?

boost::lambda

最佳答案

map迭代器会给你一个 pair其中 firstint键和 second是 map 的pair值,所以如果你有一个迭代器 it ,你会想要所有 it->second.first 中的最小值值。 min_element函数需要一个用于其第三个参数的比较函数,因此您需要构建一个投影 second.first 的比较函数它的两个参数。

我们将从一些 typedef 开始,以使代码更具可读性:

typedef std::pair<short, float> val_type;
typedef std::map<int, val_type> map_type;
map_type m;

我们将对其重载运算符使用 Boost.Lambda,允许我们使用 operator< . Boost.Bind 可以绑定(bind)成员变量和成员函数,因此我们也将利用它。

#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
using boost::bind;

// Comparison is (_1.second.first < _2.second.first)
std::cout <<
  std::min_element(m.begin(), m.end(),
    bind(&val_type::first, bind(&map_type::iterator::value_type::second, _1))
    <
    bind(&val_type::first, bind(&map_type::iterator::value_type::second, _2))
  )->second.first;

这也适用于 boost::lambda::bind .

关于c++ - 如何在复合类型上使用 Boost.Bind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4795512/

相关文章:

c++ - 如何用链表替换 std::vector?

c++ - 返回捕获引用的lambda

c++ - 如何定义和使用 boost::function with "optional arguments"?

c++ - Boost::function 绑定(bind)成员函数失效

c++ - Boost::Lambda 中的 ref()?

c++ - 无法从文件中删除行,使用 stringstream 作为替代?

c++ - 在基初始化未定义行为之前的构造期间对静态成员函数的评估是什么?

c++ - 如何将 boost 绑定(bind)与成员函数一起使用

c++ - 将 boost::lambda::bind 的返回值赋给对象?

c++ - lambda 表达式中的 return 语句