天天看点

C++一元谓词和二元谓词

一元谓词

#include <iostream>
#include <algorithm> //算法头文件
#include <list>
#include <vector>
using namespace std;

// 返回类型为bool类型 的operator()
struct GreatStruct
{
    // 一元谓词 接受一个参数
    bool operator()(int value)
    {
        return value > 5;
    }
};
// for_each需要使用的伪函数
template <typename T>
void printer(const T &val)
{
    cout << val << " ";
}
void text()
{
    // 一元谓词
    list<int> lst;
    for (int i = 0; i < 10; i++)
    {
        lst.push_back(i);
    }
    // 返回类型为一个迭代器
    auto it = find_if(lst.begin(), lst.end(), GreatStruct());
    if (it == lst.end())
    {
        cout << "没有找到 > 5 的元素" << endl;
    }
    else
    {
        cout << "找到了第一个大于5的元素:" << *it << endl;
    }
}

int main(int argc, char **argv)
{
    text();
    return 0;
}

           

二元谓词

```cpp
/*
 * @Author: Stylle
 * @Date: 2020-08-26 10:26:09
 * @LastEditors: Stylle
 * @LastEditTime: 2020-08-26 10:57:28
 * @FilePath: \learing-master\一元谓词和二元谓词.cpp
 */
#include <iostream>
#include <algorithm> //算法头文件
#include <list>
#include <vector>
using namespace std;

// 返回类型为bool类型 的operator()
struct GreatStruct
{
    // 一元谓词 接受一个参数
    bool operator()(int value)
    {
        return value > 5;
    }
};

class GreatClass
{
public:
    // 二元谓词 接受两个参数
    bool operator()(int num1, int num2)
    {
        return num1 > num2;
    }
};
// for_each需要使用的伪函数
template <typename T>
void printer(const T &val)
{
    cout << val << " ";
}
void text()
{
    // 一元谓词
    list<int> lst;
    for (int i = 0; i < 10; i++)
    {
        lst.push_back(i);
    }
    // 返回类型为一个迭代器
    auto it = find_if(lst.begin(), lst.end(), GreatStruct());
    if (it == lst.end())
    {
        cout << "没有找到 > 5 的元素" << endl;
    }
    else
    {
        cout << "找到了第一个大于5的元素:" << *it << endl;
    }
    // 二元谓词 list不支持随机访问所以不能使用sort访问这里改用vector容器
    vector<int> v;
    v.push_back(10);
    v.push_back(5);
    v.push_back(13);
    v.push_back(8);
    v.push_back(2);
    // 默认策略为从小到大排序
    sort(v.begin(), v.end());
    for_each(v.begin(), v.end(), printer<int>);
    cout << endl;
    // 修改sort排序策略为从大到小 (匿名函数对象)
    sort(v.begin(), v.end(), GreatClass());
    for_each(v.begin(), v.end(), printer<int>);
    cout << endl;
}

int main(int argc, char **argv)
{
    text();
    return 0;
}
           

一元谓词和二元谓词的区别以及谓词的作用

区别:接受1个参数的谓语是一元,两个是二元.

作用:谓语是返回bool値的通常作为算法的判断条件的辅助函数,并且谓语对于某个数永远返回一样的値.也就是谓语函数Pre(),不能现在接受参数a返回true,等下返回false.

所以本身有状态并且影响返回结果的辅助函数都不能叫做谓语.比如有static变量作为状态的函数和有内部参数的函数对象.

来自:“the C++ standard library”