std::find 是 C++ STL 中用于线性查找第一个匹配元素的算法,需包含 头文件,接受起始迭代器、结束迭代器和待查值三个参数,返回指向匹配元素的迭代器或 end()。

find 是 C++ STL 中最常用的查找算法之一,它在指定范围内线性搜索第一个匹配的元素,返回指向该元素的迭代器;如果没找到,就返回范围末尾的迭代器(通常是 end())。
基本用法:需要头文件和三个参数
使用 std::find 前要包含 头文件。它接受三个参数:
- 起始迭代器(如
v.begin()) - 结束迭代器(如
v.end(),注意不包含该位置) - 要查找的值(类型需与容器元素可比较)
例如,在 vector 中找数字 7:
#include
#include
#include
std::vectorv = {1, 5, 7, 3, 7, 9};
auto it = std::find(v.begin(), v.end(), 7);
if (it != v.end()) {
std::cout << "找到,索引为:" << (it - v.begin()) << std::endl;
} else {
std::cout << "未找到" << std::endl;
支持所有支持迭代器的容器
不只是 vector,find 可用于 list、deque、array、string,甚至原生数组(配合指针):
立即学习“C++免费学习笔记(深入)”;
std::string s = "hello"; auto it = std::find(s.begin(), s.end(), 'l');int arr[] = {2,4,6}; auto it = std::find(std::begin(arr), std::end(arr), 4);
注意:map 和 unordered_map 不适合直接用 find 查 value(效率低),它们自带更高效的 find() 成员函数查 key。
自定义类型查找:必须支持 == 比较
若容器存的是自定义结构体或类,需重载 operator==,否则编译失败:
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
std::vector people = {{"Alice", 30}, {"Bob", 25}};
auto it = std::find(people.begin(), people.end(), Person{"Bob", 25}); 找不到时返回 end(),务必检查再解引用
这是常见错误来源:直接对返回的迭代器取值而不判断是否有效,会导致未定义行为:
- ✅ 正确:
if (it != container.end()) { use *it; } - ❌ 危险:
std::cout (万一没找到)
对 string 或 vector 等连续容器,也可用 it - begin() 得到下标;但对 list 这类链表,只能用 std::distance(begin(), it) 计算位置。








