count : 在序列中統計某個值出現的次數 count_if : 在序列中統計與某謂詞匹配的次數
count和count_if函數是計數函數,先來看一下count函數:
count函數的功能是:統計容器中等於value元素的個數。
先看一下函數的參數:
count(first,last,value); first是容器的首迭代器,last是容器的末迭代器,value是詢問的元素。
可能我說的不太詳細,來看一個例題:
給你n個數字(n<=1000),再給你一個數字m,問你:數字m在n個數字中出現的次數。
看到這道題,我們會想到使用sort+equal_range函數的配合(n的范圍大約在1萬---10萬左右),不過n<=1000 數據量不大,所以我們可以直接使用count函數,這里我們要注意一點:count函數的復雜度是線性的,最壞情況是O(n)。這題很簡單,所以我們很快就可以寫出代碼:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 int main() 7 { 8 int n; 9 vector <int> V; 10 cin>>n; 11 for(int i=0;i<n;i++) 12 { 13 int temp; 14 cin>>temp; 15 V.push_back(temp); 16 } 17 int ask; 18 while(cin>>ask) 19 { 20 int num=count(V.begin(),V.end(),ask); 21 cout<<num<<endl; 22 } 23 return 0; 24 }
但是,假如我們要使用STL的函數 統計1-10奇數的個數,怎么辦呢?
所以,我們就需要使用count_if函數,這是一個很有用的函數,我們要重點介紹它。
看一下count_if函數的參數:
count_if(first,last,value,cmp); first為首迭代器,last為末迭代器,value為要查詢的元素,cmp為比較函數。
其實cmp比較函數才是整個count_if函數的核心,cmp比較函數是編程的人寫的,返回值是一個布爾型,我相信看完我的例題后,就可以理解這個函數的應用。例題:統計1-10奇數的個數(我的代碼):
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <vector> 5 using namespace std; 6 bool comp(int num) 7 { 8 return num%2; 9 } 10 int main() 11 { 12 vector <int> V; 13 for(int i=1;i<=10;i++) 14 V.push_back(i); 15 cout<<count_if(V.begin(),V.end(),comp)<<endl; 16 return 0; 17 }
例:
1 //統計成績大於90 2 3 #include <iostream> 4 #include <cstdio> 5 #include <cstring> 6 #include <vector> 7 #include <algorithm> 8 using namespace std; 9 struct student 10 { 11 string name; 12 int score; 13 }; 14 bool compare(student a) 15 { 16 return 90<a.score; 17 } 18 int main() 19 { 20 int n; 21 cin>>n; 22 vector<student> V; 23 for(int i=0;i<n;i++) 24 { 25 student temp; 26 cin>>temp.name>>temp.score; 27 V.push_back(temp); 28 } 29 cout<<count_if(V.begin(),V.end(),compare)<<endl; 30 return 0; 31 }
原文鏈接:https://www.cnblogs.com/Roni-i/p/8675528.html
