count_if用于统计满足条件的元素个数,all_of用于判断所有元素是否都满足条件,二者均通过谓词进行判断,可结合Lambda表达式简化使用,在处理复杂数据时需设计合适的谓词,并注意其线性时间复杂度带来的性能影响。

统计满足条件的元素个数,以及判断是否所有元素都满足条件,这就是
count_if
all_of
count_if
#include <iostream>
#include <vector>
#include <algorithm>
bool isEven(int i) { return (i % 2) == 0; }
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
int evenCount = std::count_if(numbers.begin(), numbers.end(), isEven);
std::cout << "偶数个数: " << evenCount << std::endl; // 输出: 偶数个数: 3
return 0;
}all_of
true
false
#include <iostream>
#include <vector>
#include <algorithm>
bool isPositive(int i) { return i > 0; }
int main() {
std::vector<int> numbers1 = {1, 2, 3, 4, 5, 6};
std::vector<int> numbers2 = {-1, 2, 3, 4, 5, 6};
bool allPositive1 = std::all_of(numbers1.begin(), numbers1.end(), isPositive);
bool allPositive2 = std::all_of(numbers2.begin(), numbers2.end(), isPositive);
std::cout << "numbers1 所有元素都大于 0: " << std::boolalpha << allPositive1 << std::endl; // 输出: numbers1 所有元素都大于 0: true
std::cout << "numbers2 所有元素都大于 0: " << std::boolalpha << allPositive2 << std::endl; // 输出: numbers2 所有元素都大于 0: false
return 0;
}count_if
all_of
Lambda 表达式允许你定义匿名函数,可以直接在
count_if
all_of
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
// 使用 lambda 表达式统计偶数个数
int evenCount = std::count_if(numbers.begin(), numbers.end(), [](int i){ return (i % 2) == 0; });
std::cout << "偶数个数: " << evenCount << std::endl;
// 使用 lambda 表达式检查所有元素是否都大于 0
bool allPositive = std::all_of(numbers.begin(), numbers.end(), [](int i){ return i > 0; });
std::cout << "所有元素都大于 0: " << std::boolalpha << allPositive << std::endl;
return 0;
}使用 Lambda 表达式的好处是代码更简洁,尤其是在谓词逻辑比较简单的情况下。 它可以直接嵌入到算法调用中,避免了单独定义函数的开销。
count_if
all_of
在处理复杂数据时,你需要根据数据的结构和需要满足的条件来设计谓词。 例如,假设你有一个
Student
#include <iostream>
#include <vector>
#include <algorithm>
class Student {
public:
std::string name;
int age;
double score;
Student(std::string name, int age, double score) : name(name), age(age), score(score) {}
};
int main() {
std::vector<Student> students = {
{"Alice", 20, 85.0},
{"Bob", 17, 60.0},
{"Charlie", 19, 90.0},
{"David", 21, 55.0}
};
// 统计年龄大于 18 岁的学生人数
int adultCount = std::count_if(students.begin(), students.end(), [](const Student& s){ return s.age > 18; });
std::cout << "年龄大于 18 岁的学生人数: " << adultCount << std::endl;
// 检查是否所有学生的成绩都及格(>= 60)
bool allPassed = std::all_of(students.begin(), students.end(), [](const Student& s){ return s.score >= 60.0; });
std::cout << "所有学生的成绩都及格: " << std::boolalpha << allPassed << std::endl;
return 0;
}在这个例子中, Lambda 表达式访问了
Student
count_if
all_of
虽然
count_if
all_of
以下是一些优化建议:
count_if
all_of
此外,如果你的容器是有序的,并且谓词也具有某种单调性,那么可以考虑使用二分查找等更高效的算法来替代
count_if
all_of
以上就是C++STL算法count_if和all_of使用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号