120.C++谓词
120.C++谓词
1.定义
C++中的谓词:返回值为bool类型的仿函数;
一元谓词:operator() 函数接收一个参数;
二元谓词:operator() 函数接收两个参数。
补充:函数对象
重载函数调用操作符的类,其对象常称为函数对象。
函数对象使用重载的小括号时,其行为类型函数,因此也叫仿函数。
本质:
函数对象是一个类,而非一个函数,我们下面的匿名对象就是一个函数对象。
2.一元谓词
例子:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Person
{
public:
bool operator()(int v) // 一元谓词
{
return v > 50;
}
};
void CoutVector(vector<int>v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << *it << ' ';
}
cout << endl;
}
void test01()
{
vector<int>v;
for (int i = 0; i < 6; ++i)
{
v.push_back(rand() % 100);
}
// 查找大于50的数字
vector<int>::iterator it = find_if(v.begin(), v.end(), Person());
cout << " 大于50的数字->";
if (it != v.end())
cout << "找到了:" << *it << endl;
else
cout << "找不到" << endl;
CoutVector(v);
}
int main()
{
test01();
return 0;
}
输出:
大于50的数字->找到了:67
41 67 34 0 69 24
3.二元谓词
例子:
class Person
{
public:
bool operator()(int v) // 一元谓词
{
return v > 0;
}
bool operator()(int v1, int v2) // 二元谓词
{
return v1 >= v2;
}
};
// 打印函数
void CoutVector(vector<int>v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << *it << ' ';
}
cout << endl;
}
void test02()
{
vector<int>v;
for (int i = 0; i < 6; ++i)
{
v.push_back(rand() % 100);
}
CoutVector(v);
cout << "升序排序" << endl;
sort(v.begin(), v.end());
CoutVector(v);
cout << "降序排序" << endl;
sort(v.begin(), v.end(), Person()); // Person() 是一个匿名函数对象,也就是仿函数
CoutVector(v);
}
输出:
41 67 34 0 69 24
升序排序
0 24 34 41 67 69
降序排序
69 67 41 34 24 0
参考:【c++ -- 谓词】
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)