c++ - 帮助理解 boost::bind 占位符参数

标签 c++ boost

我正在阅读 StackOverFlow 上一篇关于按对的第二个元素对 vector 对进行排序的帖子。最明显的答案是创建一个谓词,但一个使用 boost 的答案引起了我的注意。

std::sort(a.begin(), a.end(), 
  boost::bind(&std::pair<int, int>::second, _1) <
  boost::bind(&std::pair<int, int>::second, _2));

我一直在试图弄清楚 boost::bind 是如何工作的,或者至少只是如何使用它,但我无法弄清楚占位符参数 _1 和 _2 的目的是什么,以及 boost 文档根本不会陷进去。

谁能解释一下 boost::bind 的具体用法?

附言原题:How do I sort a vector of pairs based on the second element of the pair?

最佳答案

这个表达式:

boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2)

即,使用 <运算符实际上在另外两个仿函数之间定义了一个仿函数,这两个仿函数都由 bind 定义。 .

sort 期望的仿函数需要有一个 operator()看起来像这样:

bool operator()(const T& arg1, const T& arg2);

当您使用 boost 的 < 创建仿函数时然后名称持有者_1_2对应arg1arg2你正在创建的仿函数。

bind call 创建一个调用 ::second 的仿函数的 arg1arg2

幸运的是,在 C++0x 中引入 lambda 将使这样的表达式过时。

关于c++ - 帮助理解 boost::bind 占位符参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2120725/

相关文章:

c++ - Boost 1.56 with QT creator, "LNK1104: cannot open file ' libboost_unit_test_framework-vc100-mt-gd-1_56.lib'”

c++ - boost::hana 如何检查类型是否为 std::optional?

c++ - 如何将 Eigen::eigenvector().col(0).real() 转换为 std vector ?

c++ - 如何访问 child 的 protected 变量

c++ - 错误 LNK2019 : unresolved external symbol "public: __thiscall Signal

c++ - 如何在不复制数据的情况下从类中返回大 vector

C++ STL : Why do STL data structures not provide a function for measuring the memory consumption?

c++ - 是否有必要释放 shared_ptr?

c++ - 遍历 uBlas 稀疏矩阵的非零元素

c++ - Boost C++ 示例代码 - 静态编译错误