理解sort和binary_function中谓词的使用
Understanding use of predicates in sort and binary_function
我有下面的代码片段,它作为排序函数的谓词。这是为了排序哈希映射中的值对,我把它放在一个向量中。对向量
进行排序 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中,函数的这种用法可以用匿名函数代替。
相关文章:
- "error: no matching function for call to"构造函数错误
- std::condition_variable::wait()如何评估给定的谓词
- 调用专用模板时出错"no matching function for call to [...]"
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- "no matching function for call to 'Vector::Vector'"错误
- 如何在向量中删除 std::function<void()>?
- 不断"Attempting to reference a deleted function"
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 如何正确使用 std::function 作为谓词