c++ 标准模板库(STL) 谓词(predicate) 详细介绍

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89597427

1. 定义
The Predicate parameter is used whenever an algorithm expects a function object that when applied to the result of dereferencing the corresponding iterator returns a value testable as true. In other words, if an algorithm takes Predicate pred as its argument and first as its iterator argument, it should work correctly in the construct if (pred(*first)){...}. The function object pred shall not apply any non-constant function through the dereferenced iterator. This function object may be a pointer to function, or an object of a type with an appropriate function call operator.
当一个算法需要一函数对象,去应用于解引用(deferencing)迭代器(deferencing 解释: int p;将定义一个指向整数的指针,并p取消引用该指针,这意味着它将实际检索p指向的数据。)的结果,谓词参数返回一个testable值为true。换句话说,换句话说, 如果算法将谓词 pred 作为其参数,first参数是迭代参数,则如果 (pred (* first)) {..} , 它应该在构造中正常工作。函数对象 pred 不应通过解引用迭代器应用于任何非定常(non-constant)函数。此函数对象可以是指向函数的指针, 也可以是具有适当函数调用运算符的类型的对象。
2. 简单释义

如果你写的函数对象接受一个参数,那么就叫 一元函数对象
如果你写的函数对象接受两个参数,那么叫 二元函数对象
如果你写的函数对象或者普通函数接受一个参数,并且返回值是Bool,叫一元谓词
如果你写的函数对象或者普通函数接受二个参数,并且返回值是Bool,叫二元谓词
3. 举例说明
1) 一元谓词

//一元谓词 应用举例:find_if
class mycompare{
public:
    bool operator()(int v){
        if (v > 7){
            return true;
        }
        else{
            return false;
        }
    }
};

vector<int> v;
for (int i = 0; i < 10; i++){
    v.push_back(i);
}
vector<int>::iterator pos = find_if(v.begin(), v.end(), mycompare()); //匿名函数对象
if(pos == v.end()){
    cout << "没找到" << endl;
}
else{
cout << "找到:" << *pos << endl;
}
2)二元谓词

//二元函数对象 应用举例 : transform
class myplus{
public:
    int operator()(int v1,int v2){
        return v1 + v2;
    }
    
};

vector<int> v1,v2,v3;
for (int i = 0; i < 10; i++){
    v1.push_back(i);
    v2.push_back(i + 1);
}
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), myplus()); //匿名函数对象

 

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89597427