温馨提示×

如何用count_if统计容器元素

c++
小樊
87
2024-08-23 17:58:29
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用count_if函数来统计容器中满足特定条件的元素个数。

例如,如果要统计一个vector中大于10的元素个数,可以这样写:

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

int main() {
    std::vector<int> vec = {5, 10, 15, 20, 25, 30};
    
    int count = std::count_if(vec.begin(), vec.end(), [](int i) { return i > 10; });
    
    std::cout << "大于10的元素个数为: " << count << std::endl;
    
    return 0;
}

运行结果将输出:

大于10的元素个数为: 4

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++ set count怎样快速统计元素

0