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

   2024-10-01 2340
核心提示:在C++中,可以使用STL中的count_if函数来统计满足特定条件的元素个数。该函数位于algorithm头文件中。下面是一个简单的示例,演

在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变量,最终输出结果。

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

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