📅  最后修改于: 2023-12-03 15:29:42.123000             🧑  作者: Mango
count_if()
是C++ STL(标准模板库)中的一个算法,用于统计指定范围内满足条件的元素个数。它具有高度的通用性,因为它能够与多种容器类型(如vector、list、set等)和自定义数据类型一起使用。
以下是count_if()
函数的语法:
template<class InputIt, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPredicate p);
其中:
InputIt
:输入迭代器的类型UnaryPredicate
:一元谓词的类型,其中一元谓词是一个指向接受单个参数的函数或可调用对象的指针或函数对象first
:定义要计数的元素范围的起始位置的迭代器last
:定义要计数的元素范围的结束位置的迭代器p
:一元谓词,用于指定要检查的条件函数返回一个整数,表示满足给定条件的元素的数量。
以下代码演示了如何使用count_if()
函数来计算vector中大于10的元素的数量:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 5, 8, 13, 17, 20};
int count = std::count_if(v.begin(), v.end(), [](int i) {
return i > 10; });
std::cout << "Number of elements greater than 10: " << count << std::endl;
return 0;
}
输出结果如下:
Number of elements greater than 10: 3
使用自定义谓词可以进一步灵活地使用count_if()
函数。以下代码演示了如何使用自定义谓词来计算vector中元素位数小于4的数量:
#include <iostream>
#include <vector>
#include <algorithm>
bool less_than_4_digits(int n) {
int count = 0;
while (n) {
count++;
n /= 10;
}
return count < 4;
}
int main() {
std::vector<int> v = {12, 123, 456, 7890, 99999};
int count = std::count_if(v.begin(), v.end(), less_than_4_digits);
std::cout << "Number of elements with less than 4 digits: " << count << std::endl;
return 0;
}
输出结果如下:
Number of elements with less than 4 digits: 3
count_if()
是一个强大的功能,它能够轻松地对各种容器和数据类型执行计数操作,并且使用自定义谓词可以进一步灵活地使用它。熟练掌握count_if()
可以提高代码的效率和可读性。