理解sort和binary_function中谓词的使用

Understanding use of predicates in sort and binary_function

本文关键字:谓词 function sort binary 理解      更新时间:2023-10-16

我有下面的代码片段,它作为排序函数的谓词。这是为了排序哈希映射中的值对,我把它放在一个向量中。对向量

进行排序
  struct val_less : binary_function<pair<string, unsigned int>, pair<string, unsigned int>,     bool>
{
    bool operator() ( pair<string, unsigned int>&x , pair<string, unsigned int> &y )
    const {
        return x.second>y.second;
    }

}val_gt;

我明白代码在做什么,但我不明白为什么要这样做。什么是binary_function,为什么我们需要使用它作为":"。operator()函数是什么,为什么是bool operator()。我理解的参考参数,因为我们想改变原来的向量。

谢谢

binary_function是排序函数的基类:

http://www.cplusplus.com/reference/functional/binary_function/

的语法:

struct val_less : binary_function<pair<string, unsigned int>, pair<string, unsigned int>,     bool>

表明你的结构是binary_function模板实例化的衍生物。":"表示继承。

此外,该结构体在c++中作为函子类型工作——操作符()被重写,排序函数将使用它进行比较。在c++ 11中,函数的这种用法可以用匿名函数代替。