• algorithm库———count&&countif


    algorithm头文件定义了一个count的函数,其功能类似于find。这个函数使用一对迭代器和一个值做参数,返回这个值出现次数的统计结果。

    编写程序读取一系列int型数据,并将它们存储到vector对象中,然后统计某个指定的值出现了多少次

    count(数组开头,数组结尾,数组要找的对象);

    核心代码:cout<<count(ivec.begin() , ivec.end() , searchValue);

    样例:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int main()
    {
    int a[1000],n;
    scanf("%d",&n);
    for(int i = 0;i < n; i++)
    {
    scanf("%d",a + i);
    }
    int m;
    scanf("%d",&m);
    printf("%d ",count(a,a+n,m));
    return 0;
    }

    有了这个函数,就不用循环一个一个搜索了!!!

    这里还有一个更强的函数:count_if

    count_if(数组开头,数组结尾,要满足的条件【1】)

    【1】:满足条件可以用自定义函数,定义函数,返回判断值。

    样例:

        #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>::size_type  result1 = count_if(v1.begin(), v1.end(), greater10);  //count_if算法返回使谓词函数返回条件成立的元素个数  
            cout << "The number of elements in v1 greater than 10 is: "  
                 << result1 << "." << endl;  
          
            return 0;  
        }  

    最后,阿姆镇楼!!!

    只想找一个不会伤害我的人
  • 相关阅读:
    设计模式 对象结构型 代理模式
    设计模式 对象/类结构型 适配器模式
    设计模式 创建型 原型模式
    设计模式 创建型 建造模式
    Django REST framework使用及源码分析之权限
    Django REST framework使用及源码分析之验证
    某游戏公司运维开发python笔试题
    django中间件的5个方法以及csrf的装饰器用法
    Django源码理解一
    消息中间件-RabbitMQ
  • 原文地址:https://www.cnblogs.com/DukeLv/p/7911524.html
Copyright © 2020-2023  润新知