谓词

一、谓词概念

  • 返回bool类型的仿函数称为谓词
  • 如果operator()接收一个参数,叫一元谓词
  • 如果operator()接受两个参数,叫二元谓词

1.一元谓词

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class GreateV
{
public:
    bool operator()(int val)
    {
        return val > 5;
    }

};
void test1()
{
    vector<int> mv;
    for (int i = 0; i < 10; i++)
    {
        mv.push_back(i);
    }
    //查找容器中,有没有大于5的数字
    //GreateV()是匿名的函数对象,
    vector<int>::iterator it = find_if(mv.begin(), mv.end(), GreateV());//返回一个迭代器,条件成立的位置
    if (it == mv.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到了大于5的数字" << *it <<endl;
    }
    
}

int main()
{
    test1();
    system("pause");
}

2.二元谓词

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

class printVec
{
public:
    void operator()(vector<int> &mv)
    {
        for (vector<int>::iterator m = mv.begin(); m!=mv.end();m++ )
        {
            cout << *m << endl;
        }
    }
};

class Print
{
public:
    bool operator()(const int &mv1, const int &mv2)
    {
        return mv1 > mv2;
    }
};
void test1()
{
    vector<int> mv;
    printVec pv;//声明一个仿函数的类
    mv.push_back(10);
    mv.push_back(20);
    mv.push_back(40);
    mv.push_back(30);
    //sort(mv.begin(), mv.end());//默认从小到大排序
    sort(mv.begin(), mv.end(), Print());//从大到小
    pv(mv);
}

int main()
{
    test1();
    system("pause");
}