C++標準模板庫函式,返回在[first, last)範圍內滿足特定條件的元素的數目。重要的元素是等於value的第一個版本,第二個版本計算元素的謂詞p回報true.
基本介紹
- 中文名:count_if
- 頭檔案:#include<algorithm>
- 語言:C++
函式功能
函式原型
template<class InputIterator, class Predicate> typename iterator_traits<InputIterator>::difference_type count_if( InputIterator _First, InputIterator _Last, Predicate _Pred );
輸入參數
_Last 輸入疊代器,指向將被搜尋的區間最後一個元素後面的。
_Pred 用戶自定義的 predicate function object ,定義了元素被計數需滿足的條件。
predicate 只帶一個參數,返回 true 或 false.
返回值
複雜性
示例代碼
實例一
#include <vector>#include <algorithm>#include <iostream>bool greater10(int value){ return value >10;}int main(){ using namespace std; vector<int> v1; vector<int>::iterator Iter; v1.push_back(10); v1.push_back(20); v1.push_back(10); v1.push_back(40); v1.push_back(10); cout << "v1 = ( "; for (Iter = v1.begin(); Iter != v1.end(); Iter++) cout << *Iter << " "; cout << ")" << endl; vector<int>::iterator::difference_type result1; result1 = count_if(v1.begin(), v1.end(), greater10); cout << "The number of elements in v1 greater than 10 is: " << result1 << "." << endl;}
運行結果
v1 = ( 10 20 10 40 10 )The number of elements in v1 greater than 10 is: 2.
實例二
//VC6.0下編譯運行會報錯#include <iostream>#include <vector>#include <algorithm>using namespace std;template <typename elementType>bool IsEven(const elementType& number){ return ((number % 2 )==0);}int main(){ vector<int> vecIntegers; for (int nNum=-9; nNum<10;++nNum) { vecIntegers.push_back(nNum); } vector<int>::const_iterator iElementLocator; for (iElementLocator=vecIntegers.begin(); iElementLocator != vecIntegers.end(); ++iElementLocator) { cout << *iElementLocator << ' '; } cout << endl; size_t nNumEvenElements = count_if(vecIntegers.begin(), vecIntegers.end(), IsEven<int>); cout << "vector里有" << vecIntegers.size() << "個數,其中偶數有" << nNumEvenElements << "個" << endl << endl; return 0;}