我正在阅读 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
对应arg1
和 arg2
你正在创建的仿函数。
bind
call 创建一个调用 ::second
的仿函数的 arg1
和 arg2
幸运的是,在 C++0x 中引入 lambda 将使这样的表达式过时。
关于c++ - 帮助理解 boost::bind 占位符参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2120725/