C++提高编程 4 STL -谓词

4.2 谓词

4.2.1  谓词概念

概念:

返回bool类型的仿函数称为谓词(Pred)

返回operator()接受一个参数,那么叫做一元谓词

返回operator()接受两个参数,那么叫做两元谓词

 

4.2.2  一元谓词

复制代码
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>

//仿函数  返回值类型是bool数据类型,称为谓词
//一元谓词

class GreaterFive
{
public:
    bool operator()(int val)
    {
        return val > 5;
    }
};



void test1()
{
    vector<int>v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    //查找容器中有没有大于5的数字
    //GreaterFive() 匿名对象
    vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
    if (it == v.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到了" << endl;
    
        //不用再用for循环遍历了 因为此时的it已经是大于5的数字了 直接输出*it即可
        //for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
        //{
        //    cout << *it << endl;
        //}                
        cout << *it << endl;
    }


}

int main()
{
    test1();

    system("pause");
    return 0;
}
复制代码

 

4.2.2  二元谓词

复制代码
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>

//二元谓词
class myCompare
{
public:
    bool operator()(int val1, int val2)
    {
        return val1 > val2;
    }
};

void test1()
{
    vector<int>v;
    v.push_back(10);
    v.push_back(40);
    v.push_back(20);
    v.push_back(30);
    v.push_back(50);

    sort(v.begin(), v.end());
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << "  ";            // 10 20 30 40 50
    }
    cout << endl;

    //使用函数对象  改变算法策略,变为排序规则为从大到小
    sort(v.begin(), v.end(), myCompare());

    cout << "------------------" << endl;
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << "  ";            // 50 40 30 20 10
    }
    cout << endl;
}

int main()
{
    test1();

    system("pause");
    return 0;
}
复制代码

 

posted @   大白不会敲代码  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示