90.STL-谓词的使用

目录

1.什么是谓词

2.代码演示 


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++ 中使用谓词的一些基本概念。以下是对代码的解释:

  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 谓词将学生按年龄升序排序,然后打印排序后的学生信息。

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

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清酒。233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值