目录
1.什么是谓词
在C++中,谓词(Predicate)是指一种能够判断某个条件是否满足的可调用对象,通常是函数或者函数对象。谓词通常用于算法中,用于指定某种条件或规则,例如在排序、查找、删除等算法中指定元素的判定规则。
概念:
- 返回bool类型的仿函数称为谓词
- 如果operator()接受一个参数,那么叫做一元谓词
- 如果operator()接受两个参数,那么叫做二元谓词
2.代码演示
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
class Student {
public:
string _name;
int _age;
Student() {}
Student(string name, int age) : _name(name), _age(age) {}
void desc() const {
cout << "name:" << _name << " age:" << _age << endl;
}
};
// 一元谓词
class Younger {
public:
bool operator()(const Student& s1) const {
return s1._age < 18;
}
};
// 二元谓词
class AgeComparator {
public:
bool operator()(const Student& s1, const Student& s2) const {
return s1._age < s2._age;
}
};
void test01() {
vector<Student> v;
v.push_back(Student("xiaoming", 19));
v.push_back(Student("xiaolv", 20));
v.push_back(Student("xiaohei", 17));
v.push_back(Student("xiaohong", 16));
v.push_back(Student("xiaolan", 21));
v.push_back(Student("xiaozi", 18));
// 需求:从容器中找到第一个未成年的学生
vector<Student>::iterator it = find_if(v.begin(), v.end(), Younger());
if (it == v.end()) {
cout << "没找到" << endl;
}
else {
cout << "找到了" << endl;
(*it).desc();
}
// 需求:将容器中的元素按年龄进行排序
sort(v.begin(), v.end(), AgeComparator());
cout << "排序:" << endl;
for (const Student& s : v) {
s.desc();
}
}
int main() {
test01();
return 0;
}
这段代码展示了 C++ 中使用谓词的一些基本概念。以下是对代码的解释:
Student 类定义:
Student
类表示学生,包含两个公有成员_name
和_age
分别表示学生的姓名和年龄。desc()
函数用于打印学生的姓名和年龄。Younger 类(一元谓词):
Younger
是一个谓词类,实现了operator()
函数,接受一个Student
对象并返回布尔值。- 这个谓词用于判断一个学生是否未成年,规定未成年的标准是年龄小于 18 岁。
AgeComparator 类(二元谓词):
AgeComparator
是另一个谓词类,实现了operator()
函数,接受两个Student
对象并返回布尔值。- 这个谓词用于在排序时比较两个学生的年龄,以便将学生按年龄升序排列。
test01() 函数:
- 创建了一个存储
Student
对象的向量v
,并向其中添加了几个学生。- 使用
find_if
函数和Younger
谓词找到第一个未成年的学生,并打印其信息。- 使用
sort
函数和AgeComparator
谓词将学生按年龄升序排序,然后打印排序后的学生信息。
写在最后:以上就是本篇文章的内容了,感谢你的阅读。如果感到有所收获的话可以给博主点一个赞哦。如果文章内容有遗漏或者错误的地方欢迎私信博主或者在评论区指出~