MST

星途 面试题库

面试题:C++ find算法在自定义结构体容器中的应用

定义一个结构体Student,包含姓名(std::string类型)和年龄(int类型)。创建一个std::vector<Student> 容器,并向其中添加若干Student对象。使用C++ STL的find算法,根据给定的姓名,查找对应的Student对象并输出其年龄。如果没找到,输出提示信息。请给出完整代码实现,同时要考虑如何让find算法能够正确比较自定义结构体对象。
33.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}