C++ count_if用法详解

   2024-10-01 2390
核心提示:在C++中,count_if是STL中的一个算法,用于计算满足指定条件的元素个数。其语法如下:template class InputIterator, class Unar

在C++中,count_if是STL中的一个算法,用于计算满足指定条件的元素个数。其语法如下:

template <class InputIterator, class UnaryPredicate>  typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

其中,firstlast 分别是要搜索的元素范围的起始和结束迭代器。pred 是一个一元谓词函数对象,用于指定满足条件的判定条件。count_if 返回一个整数,表示满足条件的元素个数。

下面是一个简单的示例,演示如何使用count_if来计算一个容器中偶数的个数:

#include <iostream>#include <vector>#include <algorithm>bool isEven(int n) {    return n % 2 == 0;}int main() {    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    int numEven = std::count_if(numbers.begin(), numbers.end(), isEven);    std::cout << "There are " << numEven << " even numbers in the vector." << std::endl;    return 0;}

在这个示例中,isEven 是一个自定义的判定条件函数,用于判断一个整数是否为偶数。count_if 函数将这个条件函数应用到容器numbers中的每个元素,并统计满足条件的元素个数。

需要注意的是,count_if 函数接受的参数是迭代器,并且可以用于任何支持迭代器的容器类型,如vectorlistset等。

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

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