• 90.STL-谓词的使用


    目录

    1.什么是谓词

    2.代码演示 


    1.什么是谓词

            在C++中,谓词(Predicate)是指一种能够判断某个条件是否满足的可调用对象,通常是函数或者函数对象。谓词通常用于算法中,用于指定某种条件或规则,例如在排序、查找、删除等算法中指定元素的判定规则。

    概念:

    • 返回bool类型的仿函数称为谓词
    • 如果operator()接受一个参数,那么叫做一元谓词
    • 如果operator()接受两个参数,那么叫做二元谓词

    2.代码演示 

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. class Student {
    6. public:
    7. string _name;
    8. int _age;
    9. Student() {}
    10. Student(string name, int age) : _name(name), _age(age) {}
    11. void desc() const {
    12. cout << "name:" << _name << " age:" << _age << endl;
    13. }
    14. };
    15. // 一元谓词
    16. class Younger {
    17. public:
    18. bool operator()(const Student& s1) const {
    19. return s1._age < 18;
    20. }
    21. };
    22. // 二元谓词
    23. class AgeComparator {
    24. public:
    25. bool operator()(const Student& s1, const Student& s2) const {
    26. return s1._age < s2._age;
    27. }
    28. };
    29. void test01() {
    30. vector v;
    31. v.push_back(Student("xiaoming", 19));
    32. v.push_back(Student("xiaolv", 20));
    33. v.push_back(Student("xiaohei", 17));
    34. v.push_back(Student("xiaohong", 16));
    35. v.push_back(Student("xiaolan", 21));
    36. v.push_back(Student("xiaozi", 18));
    37. // 需求:从容器中找到第一个未成年的学生
    38. vector::iterator it = find_if(v.begin(), v.end(), Younger());
    39. if (it == v.end()) {
    40. cout << "没找到" << endl;
    41. }
    42. else {
    43. cout << "找到了" << endl;
    44. (*it).desc();
    45. }
    46. // 需求:将容器中的元素按年龄进行排序
    47. sort(v.begin(), v.end(), AgeComparator());
    48. cout << "排序:" << endl;
    49. for (const Student& s : v) {
    50. s.desc();
    51. }
    52. }
    53. int main() {
    54. test01();
    55. return 0;
    56. }

    这段代码展示了 C++ 中使用谓词的一些基本概念。以下是对代码的解释:

    1. Student 类定义

      • Student 类表示学生,包含两个公有成员 _name_age 分别表示学生的姓名和年龄。
      • desc() 函数用于打印学生的姓名和年龄。
    2. Younger 类(一元谓词)

      • Younger 是一个谓词类,实现了 operator() 函数,接受一个 Student 对象并返回布尔值。
      • 这个谓词用于判断一个学生是否未成年,规定未成年的标准是年龄小于 18 岁。
    3. AgeComparator 类(二元谓词)

      • AgeComparator 是另一个谓词类,实现了 operator() 函数,接受两个 Student 对象并返回布尔值。
      • 这个谓词用于在排序时比较两个学生的年龄,以便将学生按年龄升序排列。
    4. test01() 函数

      • 创建了一个存储 Student 对象的向量 v,并向其中添加了几个学生。
      • 使用 find_if 函数和 Younger 谓词找到第一个未成年的学生,并打印其信息。
      • 使用 sort 函数和 AgeComparator 谓词将学生按年龄升序排序,然后打印排序后的学生信息。

    写在最后:以上就是本篇文章的内容了,感谢你的阅读。如果感到有所收获的话可以给博主点一个赞哦。如果文章内容有遗漏或者错误的地方欢迎私信博主或者在评论区指出~  

  • 相关阅读:
    详解AQS中的condition源码原理
    数字 IC 设计、FPGA 设计秋招笔试题目、答案、解析(2)2021 华为海思(上)
    问题定位总结
    应用软件漏洞排名
    Core-1684JD4八核高算力AI核心板
    SpringMVC的准备工作
    基于JavaWeb的企业公司管理系统设计与实现
    [《记忆中的曾祖母》闲笔记事集]2012年1月23日
    Koa学习4:密码加密、验证登录、颁发token、用户认证
    关于maven生命周期的理解
  • 原文地址:https://blog.csdn.net/weixin_63779802/article/details/134429044