📜  C++ STL中的count_if()(1)

📅  最后修改于: 2023-12-03 14:59:46.354000             🧑  作者: Mango

C++ STL中的count_if()

简介

count_if() 是C++ STL中的一个算法函数,其作用是统计一个区间内符合指定条件的元素数量。

函数原型:

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

其中,firstlast 表示所要统计的区间,pred 是一个一元谓词,用于指定符合什么样的条件的元素应该被统计。

函数返回值是符合条件的元素的数量。由于返回值类型是 iterator_traits<InputIterator>::difference_type,因此其值类型通常为一个带符号整数。

用法举例

下面是一个简单的例子,统计一个数组中所有大于10的元素的数量:

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

int main() {
    int nums[] = {3, 8, 12, 5, 18, 22};
    std::vector<int> vec(nums, nums + 6);
    
    int count = std::count_if(vec.begin(), vec.end(), [](int n) { return n > 10; });
    std::cout << "There are " << count << " numbers greater than 10 in the array.\n";
    return 0;
}

输出:

There are 3 numbers greater than 10 in the array.
谓词函数的编写

count_if() 的第三个参数是一个函数对象,用于指定对元素的判定条件。通常采用 lambda 表达式匿名函数的方式来编写谓词函数。例如:

int count = std::count_if(vec.begin(), vec.end(), [](int n) { return n % 2 == 0; });

上述例子的 lambda 表达式中,我们使用了求模运算符 % 来判断 n 是否为偶数。如果 n 是偶数,那么返回 true,否则返回 false。

当然,也可以使用普通的函数或函数对象作为谓词:

bool is_odd(int n) {
    return n % 2 == 1;
}

int count = std::count_if(vec.begin(), vec.end(), is_odd);
总结

count_if() 函数是 C++ STL中比较常用的算法函数之一,它可以帮助我们快速统计一个给定区间中符合指定条件的元素的数量。对count_if() 的熟练掌握,能够帮助我们在开发过程中更加高效地编写代码。