天天看點

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> );
           

繼續閱讀