C++--谓词

介绍🍗

① 可调用的表达式称为谓词,包括仿函数,自定义函数,lambda表达式。
② 接受一个参数的谓词,称为一元谓词。
③ 接受两个参数的谓词,称为二元谓词。
可调用的表达式:对于一个对象或者表达式,如果可以使用调用运算符(),就称它为可以调用的。
一元谓词
接受一个参数的谓词,称为一元谓词。


#include<algorithm>
#include <iostream>
#include <vector>
using namespace std;

//输出容器的所有元素
template<typename T>
void Show(const T& v)
{
    for (const auto x : v)
        cout << x << " ";
    cout << endl;
}

//判断奇数的函数(一个参数,返回bool)
bool is_odd_int(int i) {
    return ((i % 2) != 0);
}

//判断奇数的仿函数
class Is_odd
{
public:
    bool operator()(int x) const//只有一个参数
    {
        return x % 2 != 0;
    }
};

int main()
{
    vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};//使用vector向量
    cout << "v: ";  Show(v);

    auto res1 = find_if(v.begin(), v.end(), is_odd_int);//利用自定义的函数
    if (res1 != v.end())
        cout << "  找到了奇数" << *res1 << endl;

    //使用lambda表达式在向量v中查找
    auto res2 = find_if(v.begin(), v.end(), [](int i) { return ((i % 2) == 0); });
    if (res2 != v.end())
        cout << "  找到了偶数" << *res2 << endl;

    auto res3 = find_if(v.begin(), v.end(), Is_odd());
    if (res3 != v.end())
        cout << "  找到了偶数" << *res3 << endl;

    return 0;
}

二元谓词🍗

#include<algorithm>
#include <iostream>
#include <vector>
using namespace std;

//输出容器的所有元素
template<typename T>
void Show(const T& v)
{
    for (const auto x : v)
        cout << x << " ";
    cout << endl;
}

bool Greater(int x, int y)//自定义函数
{
    return x > y;
}

class CGreater //自定义仿函数
{
public:
    bool operator()(int x, int y)//重载()
    {
        return x > y;
    }
};

int main()
{
    vector<int> v1{3, 1, 5, 9, 7, 6, 4, 5, 10, 23, 12, 8};
    vector<int> v2;
    cout << "源数据:";  Show(v1);

    v2 = v1;
    sort(v2.begin(),v2.end());//默认为升序
    cout << "默认排序:";  Show(v2);

    v2 = v1;//重新赋值
    sort(v2.begin(), v2.end(), greater<int>());//降序排序,greater是STL内置仿函数,是二元谓词
    cout << "降序排序(STL仿函数):";  Show(v2);

    v2 = v1;//重新赋值
    sort(v2.begin(), v2.end(), [](int x, int y){return x>y;});//降序排序,利用lambda表达式
    cout << "降序排序(lambda):";  Show(v2);

    v2 = v1;//重新赋值
    sort(v2.begin(),v2.end(),Greater);//利用自定义函数进行降序排序
    cout << "降序排序(自定义函数):";  Show(v2);

    v2 = v1;//重新赋值
    sort(v2.begin(), v2.end(), CGreater());//利用自定义仿函数进行降序排序
    cout << "降序排序(自定义仿函数):";  Show(v2);

    return 0;
}

本篇完!🍗

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

码农小小苏

感谢大佬支持!!!

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

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

打赏作者

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

抵扣说明:

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

余额充值