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);

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

val:要匹配的值。

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

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

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

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

count_if

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

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

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

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

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

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

示例

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

#include <iostream>
#include <algorithm>
#include <vector>

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值