如何用count_if统计容器元素

   2024-10-01 2140
核心提示:可以使用count_if函数来统计容器中满足特定条件的元素个数。例如,如果要统计一个vector中大于10的元素个数,可以这样写:#inclu

可以使用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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号