C++20 引入了 std::ranges::count
和 std::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 表达式),接受一个元素并返回true
或false
。
3. 优点
- 简洁易用,代码可读性高。
- 避免了手动编写循环的繁琐。