C++ STL算法系列1---count函數


 

一.count函數

algorithm頭文件定義了一個count的函數,其功能類似於find。這個函數使用一對迭代器和一個值做參數,返回這個值出現次數的統計結果。

編寫程序讀取一系列int型數據,並將它們存儲到vector對象中,然后統計某個指定的值出現了多少次

核心代碼:

cout<<count(ivec.begin() , ivec.end() , searchValue)

 


具體實現:

 

 1 //讀取一系列int數據,並將它們存儲到vector對象中,
 2 //然后使用algorithm頭文件中定義的名為count的函數,
 3 //統計某個指定的值出現了多少次
 4 #include<iostream>
 5 #include<vector>
 6 #include<algorithm>
 7 using namespace std;
 8  
 9 int main()
10 {
11     int ival , searchValue;
12     vector<int> ivec;
13  
14     //讀入int型數據並存儲到vector對象中,直至遇到文件結束符
15     cout<<"Enter some integers(Ctrl+Z to end): "<<endl;
16     while(cin >> ival)
17         ivec.push_back(ival);
18  
19     cin.clear(); // 使輸入流重新有效
20  
21     //讀入欲統計其出現次數的int值
22     cout<<"Enter an integer you want to search: "<<endl;
23     cin>>searchValue;
24  
25     //使用count函數統計該值出現的次數並輸出結果
26     cout<<count(ivec.begin() , ivec.end() , searchValue)
27         <<"  elements in the vector have value "
28         <<searchValue<<endl;
29  
30     return 0;
31 }

 

 

 二.count_if函數

 

count_if :返回區間中滿足指定條件的元素數目。

template<class InputIterator, class Predicate>

   typename iterator_traits<InputIterator>::difference_type count_if(

      InputIterator _First,

      InputIterator _Last,

      Predicate _Pred

   );

Parameters

_First 輸入迭代器,指向將被搜索的區間第一個元素的位置。

_Last 輸入迭代器,指向將被搜索的區間最后一個元素后面的。

_Pred 用戶自定義的 predicate function object ,定義了元素被計數需滿足的條件。 predicate 只帶一個參數,返回 true false.

Return Value

滿足斷言(predicate)(也稱為謂詞)指定條件的元素數。

Remarks

這個模板函數是書法count的泛化版本,用斷言指定的條件代替等於一個指定的值。

Example

 1 #include <vector>
 2 #include <algorithm>
 3 #include <iostream>
 4 
 5 bool greater10(int value)
 6 {
 7     return value >10;
 8 }
 9 
10 int main()
11 {
12     using namespace std;
13     vector<int> v1;
14     vector<int>::iterator Iter;
15 
16     v1.push_back(10);
17     v1.push_back(20);
18     v1.push_back(10);
19     v1.push_back(40);
20     v1.push_back(10);
21 
22     cout << "v1 : ";
23     for (Iter = v1.begin(); Iter != v1.end(); Iter++)
24        cout << *Iter << " ";
25     cout << endl;
26 
27 
28     vector<int>::size_type  result1 = count_if(v1.begin(), v1.end(), greater10);  //count_if算法返回使謂詞函數返回條件成立的元素個數
29     cout << "The number of elements in v1 greater than 10 is: "
30          << result1 << "." << endl;
31 
32     return 0;
33 }

謂詞(predicate):是做某些檢測的函數,返回用於條件判斷的類型,指出條件是否成立

 總結:

count       :  在序列中統計某個值出現的次數

count_if   :    在序列中統計與某謂詞匹配的次數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM