题目
编写程序,系统应用 STL 核心谓词逻辑算法族:std::find_if(按谓词查找首个满足条件的元素)、std::count_if(按谓词统计满足条件的数量),以及 C++11 引入的短路判定算法 std::all_of(全满足)、std::any_of(存在任一满足)与 std::none_of(全不满足)。对考生集合进行及格线审查与异常排查。
输入格式:无需外部输入。
输出格式:输出各项谓词检索判定与统计分析结果。
数据范围与约定:谓词函数、短路求值与集合判定。
思路与算法
1. 短路求值性能std::any_of 只要遇到第一个满足条件的元素就会立刻提前返回 true,绝不遍历后续元素;std::all_of 只要遇到第一个违背条件的元素立刻返回 false。
2. find_if 的返回值防御
若没有元素匹配,find_if 返回 container.end()。必须先进行 it != container.end() 防御再进行解引用。
3. 组合谓词代码简洁性
相比于手写 for 循环加 flag 变量,调用这些语义高度清晰的标准算法不仅大幅减少了代码量,还杜绝了循环边界索引出差错的可能。
完整程序
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> roster = {
{"Alice", 85}, {"Bob", 58}, {"Charlie", 92},
{"Diana", 76}, {"Evan", 45}, {"Fiona", 89}
};
// 1. count_if: 统计不及格(< 60)的人数
int failCount = std::count_if(roster.begin(), roster.end(), [](const Student& s) {
return s.score < 60;
});
std::cout << "不及格(< 60 分)人数: " << failCount << " 人\n";
// 2. find_if: 找到首个不及格的学生
auto itFail = std::find_if(roster.begin(), roster.end(), [](const Student& s) {
return s.score < 60;
});
if (itFail != roster.end()) {
std::cout << "首个不及格学生: " << itFail->name << " (" << itFail->score << " 分)\n";
}
// 3. all_of: 是否全班成绩均不低于 40 分
bool allAbove40 = std::all_of(roster.begin(), roster.end(), [](const Student& s) {
return s.score >= 40;
});
std::cout << "全班是否均在 40 分以上: " << std::boolalpha << allAbove40 << "\n";
// 4. any_of: 是否存在满分特优生 (>= 90)
bool hasTopStudent = std::any_of(roster.begin(), roster.end(), [](const Student& s) {
return s.score >= 90;
});
std::cout << "是否存在 90 分以上特优生: " << hasTopStudent << "\n";
// 5. none_of: 是否没有人得 0 分
bool noZero = std::none_of(roster.begin(), roster.end(), [](const Student& s) {
return s.score == 0;
});
std::cout << "是否全员避开 0 分零分情况: " << noZero << "\n";
return 0;
}运行示例
输出:
不及格(< 60 分)人数: 2 人
首个不及格学生: Bob (58 分)
全班是否均在 40 分以上: true
是否存在 90 分以上特优生: true
是否全员避开 0 分零分情况: true