c++

如何在C++中使用count_if函数

小樊
88
2024-08-23 17:50:28
栏目: 编程语言

在C++中,可以使用STL中的count_if函数来统计满足特定条件的元素个数。该函数位于<algorithm>头文件中。

下面是一个简单的示例,演示如何使用count_if函数统计一个整数数组中大于10的元素个数:

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

int main() {
    std::vector<int> numbers = {5, 10, 15, 20, 25};
    
    int count = std::count_if(numbers.begin(), numbers.end(), [](int num) {
        return num > 10;
    });

    std::cout << "There are " << count << " numbers greater than 10 in the array." << std::endl;

    return 0;
}

在上面的示例中,使用count_if函数统计numbers容器中大于10的元素个数。在lambda表达式中,定义了一个条件函数,用于判断元素是否大于10。count_if函数会遍历容器中的每个元素,并将满足条件的元素个数返回给count变量,最终输出结果。

0
看了该问题的人还看了