• c++ count和count_if


    count

    algorithm头文件下的count用于元素的计数,使用对象包括vector,list,set,数组等。

    • 函数模板
    template <class InputIterator, class T>
      typename iterator_traits<InputIterator>::difference_type
        count (InputIterator first, InputIterator last, const T& val);
    
    • 1
    • 2
    • 3

    first, last:在元素序列的初始和最终位置输入迭代器。使用的范围是[first,last),它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

    val:要匹配的值。

    返回值:范围[first,last)中等于val的元素数。返回类型是有符号整数类型。

    • 函数格式
    count(begin,end,k);
    
    • 1

    关联容器map和set自带count函数,由于去重性,返回值只能是1或0,可以借此判断该元素是否存在。

    map<int,string> a;
    a.count(k)  //返回键值k出现的次数(注意是键值),结果为0或1
    set<int> b;
    b.count(k)  //返回元素k出现的次数
    
    • 1
    • 2
    • 3
    • 4

    count_if

    count_if 函数是 STL (标准模板库) 中的一个算法,它可以用来统计指定范围内满足特定条件的元素数量。

    • 函数模板
    template <class InputIterator, class UnaryPredicate>
      typename iterator_traits<InputIterator>::difference_type
        count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
    
    • 1
    • 2
    • 3

    first,last:在元素序列的初始和最终位置输入迭代器。使用的范围是[first,last])。

    pred:一元函数,接受范围内的元素作为参数,并返回一个可转换为 bool 的值。

    返回值:[first,last)应用于pred中不返回false的元素数。返回类型是有符号整数类型。

    • 函数格式
    count_if(begin,end,cmp);
    
    • 1

    示例

    一个整数数组,统计其中大于 5 的数的数量

    #include 
    #include 
    #include 
    
    using namespace std;
    
    bool greater_than_five(int i) {
        return i > 5;
    }
    
    int main() {
        vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int count = count_if(v.begin(), v.end(), greater_than_five);
        cout << "Number of elements greater than 5: " << count << endl;
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    .NET 6 轻量级 WebApi 框架 FastEndpoints 入门
    野火FPGA入门(3):简单组合逻辑
    UG画弹簧模型教程
    项目平台——测试报表的实现(六)
    STP简介
    《吐血整理》进阶系列教程-拿捏Fiddler抓包教程(16)-Fiddler如何充当第三者,再识AutoResponder标签-上篇
    解决宿主机ssh连接ubuntu虚拟机报错的问题
    Python基础之SQLite数据库
    qt绘图事件
    【WebRTC】【Unity】局域网UDP通信为何不通
  • 原文地址:https://blog.csdn.net/weixin_44347020/article/details/133882333