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