首页 > 编程语言 > 详细

c++函数对象之谓词

时间:2019-12-28 19:38:44      阅读:79      评论:0      收藏:0      [点我收藏+]

概念:

返回bool类型的仿函数被称为谓词;

如果operator()接受一个参数,那么就叫一元谓词;

如果operator()接受两个参数,那么就叫二元谓词;

一、一元谓词

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

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

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

void test01()
{
    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 << "找到了大于5的数字为: " << *it << endl;
    }

}


int main() {

    test01();

    system("pause");

    return 0;
}

二、二元谓词

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

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

};

void test01()
{
    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 << " ";
    }
    cout << endl;

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

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

}

int main() {

    test01();

    system("pause");

    return 0;
}

c++函数对象之谓词

原文:https://www.cnblogs.com/xiximayou/p/12112398.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!