温馨提示×

如何用count_if统计容器元素

c++
小樊
81
2024-08-23 17:58:29
栏目: 编程语言

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

0