count() “vs“ count_if()

//

头文件
    #include<algorithm>

01 count() 统计序列中某个值出现的次数

    01 数组 size_t count( T* a,T* b,const T& value );
    02 容器 size_t count( iterator a,iterator b,const T& value );

        return [ a,b ) 左闭右开区间中 value 出现的次数

02 count_if() 统计序列中与某谓词匹配的次数

    01 数组 size_t count( T* a,T* b,cmp );
    02 容器 size_t count( iterator a,iterator b,cmp );

        return [ a,b ) 左闭右开区间中 满足 cmp 函数 的元素个数

// 谓词(predicate) 做某些检测的函数 返回用于条件判断的类型 指出条件是否成立 

// count_if() 原码
template< class InputIterator,class Predicate >
ptrdiff_t count_if ( InputIterator first, InputIterator last, Predicate pred ) 
{
    ptrdiff_t ret=0; 

    while (first != last) 
        if (pred(*first++)) ++ret;

    return ret;
}

// 自实现 count_if() 模板 cnt_cmp
template< class in_iterator,class predicate >
ptr_diff_t cnt_cmp( in_iterator a,in_iterator b,predicate cmp )
{
    ptr_diff_t cnt=0;

    while( a!=b )
        if( cmp( *a++ ) ) ++cnt;

    return cnt;
}

// eg.count()
#include<bits/stdc++.h>
using namespace std;

vector<string> v;

int main()
{
    string s;
    int n,cnt;

    while( cin>>n )
    {
        cin.get();
        while( n-- ) { getline( cin,s ); v.push_back(s); }
        
        sort( v.begin(),v.end() );

        cnt=count( v.begin(),v.end(),v[0] );

        cout<<v[0]<<' '<<cnt<<endl;
    }    
    return 0;
}
// 4
// 123
// abc
// 123
// cmp
// 123 2

// eg.count_if()
#include<bits/stdc++.h>
using namespace std;

vector<int> v;

bool judge( int x ) { return x>11; }

int main()
{
    int n,x,cnt;

    while( cin>>n )
    {
        while( n-- ) { cin>>x; v.push_back(x); }
        
        sort( v.begin(),v.end() );

        cnt=count_if( v.begin(),v.end(),judge );

        cout<<cnt<<endl;
    }    
    return 0;
}
// 6
// 3 6 9 12 15 18
// 3

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/123614152