谓词、内建函数对象
谓词
概念:返回值为bool类型的仿函数
补充:仿函数就是对()进行重载的函数
用途:广泛应用于标准算法<algorithm.h>中,可以为标准算法增加筛选条件
分类:
-
一元谓词:仿函数的参数数量为1
-
二元谓词:仿函数的参数数量为2
class Compare2 {
public:
//二元谓词
bool operator()(int val, int val2) {
return val > val2;
}
};
void func3() {
vector<int> v;
//填充vector
v.push_back(5);
v.push_back(2);
v.push_back(6);
v.push_back(1);
//因为sort是排序算法,核心是两数对比,用二元谓词作为入参,让sort变成降序操作
sort(v.begin(), v.end(), Compare2());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
内建函数对象
概念:STL已经开发好的简单仿函数
头文件:#include <functional>
算数仿函数
除了取反仿函数是一元谓词,其他的都是二元谓词
算术仿函数 | 作用 |
---|---|
template T plus | 加法仿函数 |
template T minus | 减法仿函数 |
template T multiplies | 乘法仿函数 |
template T divides | 除法仿函数 |
template T modulus | 取模仿函数 |
template T negate | 取反仿函数 |
关系仿函数
关系仿函数 | 作用 |
---|---|
template bool equal_to | 等于 |
template bool not_equal_to | 不等于 |
template bool greater | 大于 |
template bool greater_equal | 大于等于 |
template bool less | 小于 |
template bool less_equal | 小于等于 |
逻辑仿函数
逻辑仿函数 | 作用 |
---|---|
template bool logical_and | 与 |
template bool logical_or | 或 |
template bool logical_not | 非 |