c++函数对象之谓词

概念:

返回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;
    }

}


 main() {

    test01();

    system(pause");

    return 0;
}

二、二元谓词

#include<iostream>
二元谓词
 MyCompare
{
int va11, val2)
    {
        return va11 > val2;
    }

};

v;
    v.push_back(10);
    v.push_back(40203050);

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

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

    cout << ----------------------- endl;
     endl;

}

;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...