天天看点

C++ 谓词(Predicate)与算法

谓词(Predicate),是做某些检测的函数,返回用于条件判断的类型,指出条件十分成立

以count为例,实现count 功能的有两个泛型算法count() 和count_if(),定义如下:

template< class InputIt, class T >

typename iterator_traits<InputIt>::difference_type
    count( InputIt first, InputIt last, const T &value );
           
template< class InputIt, class UnaryPredicate >

typename iterator_traits<InputIt>::difference_type
    count_if( InputIt first, InputIt last, UnaryPredicate p );
           

count 用来统计迭代器范围内某个具体的value 出现的次数

例如:

vector<int> a(10,2);
cout<<count(a.begin(),a.end(),10);
           

输出结果为: 10

count_if() 用来统计迭代器范围内使谓词为true 的元素个数

例如:

bool GT6(string& s)
{
    return s.size() >= 6;
}
vector<string>::size_type num = count_if(words.begin(),words.end(),GT6);
           

GT6() 是定义的predicate ,用来判断string 的长度是否大于或等于6;

count_if() 用来统计迭代器范围内元素是GT6() 为true 的元素个数;

PS. 在算法中使用Predicate 时,没有函数的一对括号

=========================================================

当谓词比较简短时,可以直接在算法中实现,更加简洁优雅,例如前面的GT6 和count_if可以如下使用:

count_if(words.begin(),words.end(), <span style="color:#FF0000;">[] (string s) { return s.size() >= 6; }</span> );
           

继续阅读