Skip to content

谓词

谓词的概念

概念:

  • 返回 bool 类型的仿函数称为谓词(Predicate)。
  • 如果 operator()接受一个参数,那么它就是一个一元谓词。
  • 如果 operator()接受两个参数,那么它就是一个二元谓词。

一元谓词

实例:

c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

void test01() {
    vector<int> v;
    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    // 定义一个一元谓词,判断元素是否大于5

    //查找大于5的元素
class GreaterThan5 {
public:
    bool operator()(int x) const {
        return x > 5;
    }
};

    auto it = find_if(v.begin(), v.end(), GreaterThan5() );

    if (it != v.end()) {
        cout << "找到大于5的元素: " << *it << endl;
    } else {
        cout << "没有找到大于5的元素" << endl;
    }
}

二元谓词

实例:

c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

viod test02() {
    vector<string> v;
    v.push_back("12");
    v.push_back("34");
    v.push_back("99966");
    v.push_back("785645");
    v.push_back("90");

    sort(v.begin(), v.end());
    for(auto it = v.begin(); it != v.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;

    //改变排序规则,按字符串长度排序
    sort(v.begin(), v.end(), MyCompare());
    for(auto it = v.begin(); it != v.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;

}
class MyCompare {
public:
    bool operator()(const string& s1, const string& s2) const {
        return s1.size() < s2.size();
    }
};