1. 程式人生 > >C++ STL之count函數

C++ STL之count函數

com tor LG ast count函數 div 成績 範圍 ask

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

總結:

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)。這題很簡單,所以我們很快就可以寫出代碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
    int n;
    vector <int> V;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        int temp;
        cin>>temp;
        V.push_back(temp);
    }
    int ask;
    while(cin>>ask)
    {
        int num=count(V.begin(),V.end(),ask);
        cout<<num<<endl;
    }
    return 0;
}

  

但是,假如我們要使用STL的函數 統計1-10奇數的個數,怎麽辦呢?

所以,我們就需要使用count_if函數,這是一個很有用的函數,我們要重點介紹它。

看一下count_if函數的參數:
count_if(first,last,value,cmp); first為首叠代器,last為末叠代器,value為要查詢的元素,cmp為比較函數。

其實cmp比較函數才是整個count_if函數的核心,cmp比較函數是編程的人寫的,返回值是一個布爾型,我相信看完我的例題後,就可以理解這個函數的應用。例題:統計1-10奇數的個數(我的代碼):

  

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int num)
{
    return num%2;
}
int main()
{
    vector <int> V;
    for(int i=1;i<=10;i++)
        V.push_back(i);
    cout<<count_if(V.begin(),V.end(),comp)<<endl;
    return 0;
}

  

成績大於90

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
struct student
{
    string name;
    int score;
};
bool compare(student a)
{
    return 90<a.score;
}
int main()
{
    int n;
    cin>>n;
    vector<student> V;
    for(int i=0;i<n;i++)
    {
        student temp;
        cin>>temp.name>>temp.score;
        V.push_back(temp);
    }
    cout<<count_if(V.begin(),V.end(),compare)<<endl;
    return 0;
}

C++ STL之count函數