MST

星途 面试题库

面试题:C++ find算法在自定义结构体数组中的范围查找

定义一个结构体Student,包含成员变量name(std::string类型)和score(int类型)。创建一个Student类型的数组并初始化。使用C++ STL的find算法,在数组中从第2个元素到第5个元素(含)范围内查找name为“Tom”的学生,如果找到,输出该学生的score,否则输出 -1 。请写出实现代码,并说明在这种场景下使用find算法需要注意什么。
47.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

struct Student {
    std::string name;
    int score;
};

int main() {
    Student students[] = {
        {"Alice", 85},
        {"Tom", 90},
        {"Bob", 78},
        {"Tom", 95},
        {"Eve", 88}
    };

    auto it = std::find_if(std::begin(students) + 1, std::begin(students) + 5, 
        [](const Student& s) { return s.name == "Tom"; });

    if (it != std::begin(students) + 5) {
        std::cout << it->score << std::endl;
    } else {
        std::cout << -1 << std::endl;
    }

    return 0;
}

使用find算法注意事项:

  1. 迭代器范围find 算法的前两个参数是迭代器,表示查找的范围,要确保范围的正确性,包括起始和结束迭代器的位置,这里需要从第2个元素(对应迭代器 std::begin(students) + 1)开始,到第5个元素(对应迭代器 std::begin(students) + 5)结束。
  2. 比较函数:因为 Student 结构体没有直接的比较方法,所以使用 find_if 并结合lambda表达式来自定义比较逻辑,明确如何判断找到目标元素。若使用 find 则需要重载 operator== 来比较 Student 结构体。