快速统计容器内元素出现次数 (C++20)

C++20 引入了 std::ranges::countstd::ranges::count_if,可以更方便地统计容器中元素的出现次数。

1. 示例

#include <iostream>
#include <vector>
#include <algorithm> // C++20 后可能不需要单独包含,取决于具体实现

int main() {
  std::vector<int> nums = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};

  // 统计值为3的元素个数
  size_t count_3 = std::ranges::count(nums, 3);
  std::cout << "Number of 3s: " << count_3 << std::endl;

  // 统计大于2的元素个数
  size_t count_greater_than_2 = std::ranges::count_if(nums, [](int x){ return x > 2; });
  std::cout << "Number of elements greater than 2: " << count_greater_than_2 << std::endl;

  return 0;
}

2. 说明

  • std::ranges::count(range, value): 统计 range 中等于 value 的元素个数。
  • std::ranges::count_if(range, predicate): 统计 range 中满足 predicate 的元素个数。
    • range 可以是任何支持迭代器的范围,例如 std::vector, std::array, 甚至 C 数组。
    • predicate 是一个可调用对象(函数、函数对象、Lambda 表达式),接受一个元素并返回 truefalse

3. 优点

  • 简洁易用,代码可读性高。
  • 避免了手动编写循环的繁琐。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值