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

find 是 C++ STL 中最常用的查找算法之一,它在指定范围内线性搜索第一个匹配的元素,返回指向该元素的迭代器;如果没找到,就返回范围末尾的迭代器(通常是 end())。
基本用法:需要头文件和三个参数
使用 std::find 前要包含 <algorithm></algorithm> 头文件。它接受三个参数:
- 起始迭代器(如
v.begin()) - 结束迭代器(如
v.end(),注意不包含该位置) - 要查找的值(类型需与容器元素可比较)
例如,在 vector<int></int> 中找数字 7:
#include <algorithm><br>#include <vector><br>#include <iostream><br><br>std::vector<int> v = {1, 5, 7, 3, 7, 9};<br>auto it = std::find(v.begin(), v.end(), 7);<br>if (it != v.end()) {<br> std::cout } else {<br> std::cout </int></iostream></vector></algorithm>支持所有支持迭代器的容器
不只是 vector,find 可用于 list、deque、array、string,甚至原生数组(配合指针):
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 {<br> std::string name;<br> int age;<br> bool operator==(const Person& other) const {<br> return name == other.name && age == other.age;<br> }<br>};<br><br>std::vector<person> people = {{"Alice", 30}, {"Bob", 25}};<br>auto it = std::find(people.begin(), people.end(), Person{"Bob", 25});</person>找不到时返回 end(),务必检查再解引用
这是常见错误来源:直接对返回的迭代器取值而不判断是否有效,会导致未定义行为:
- ✅ 正确:
if (it != container.end()) { use *it; } - ❌ 危险:
std::cout (万一没找到)
对 string 或 vector 等连续容器,也可用 it - begin() 得到下标;但对 list 这类链表,只能用 std::distance(begin(), it) 计算位置。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!








