#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// 定义Student结构体
struct Student {
std::string name;
int age;
};
// 定义比较函数,用于find算法
bool compareByName(const Student& a, const std::string& targetName) {
return a.name == targetName;
}
int main() {
// 创建std::vector<Student>容器
std::vector<Student> students = {
{"Alice", 20},
{"Bob", 22},
{"Charlie", 21}
};
std::string targetName = "Bob";
// 使用find算法查找学生
auto it = std::find_if(students.begin(), students.end(), [&targetName](const Student& s) {
return s.name == targetName;
});
if (it != students.end()) {
std::cout << "找到学生 " << it->name << ",年龄为 " << it->age << std::endl;
} else {
std::cout << "未找到名为 " << targetName << " 的学生" << std::endl;
}
return 0;
}