std::find 详解
1. 它是什么
std::find 定义在 <algorithm> 头文件中,用于在区间 [first, last) 中线性查找第一个等于给定值的元素。
2. 函数签名
C++17 及之前:
cpp
template <class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value);
C++20 起增加了 constexpr:
cpp
template <class InputIt, class T>
constexpr InputIt find(InputIt first, InputIt last, const T& value);
C++20 还提供了 ranges 版本(可以直接传容器,不必写 begin()/end()):
cpp
template <ranges::input_range R, class T>
constexpr ranges::borrowed_iterator_t<R> find(R&& r, const T& value);
3. 参数与返回值
| first | 起始迭代器(包含) |
| last | 结束迭代器(不包含) |
| value | 要查找的值 |
返回值:
-
找到:返回指向第一个匹配元素的迭代器;
-
没找到:返回 last。
复杂度: 最多 std::distance(first, last) 次比较,即 O(n)。
要求: 表达式 *it == value 必须合法,也就是元素类型和 value 之间要有可用的 operator==。
4. 典型用法
cpp
auto it = std::find(v.begin(), v.end(), target);
if (it != v.end()) {
// 找到了,*it 就是匹配元素
// std::distance(v.begin(), it) 是下标
} else {
// 没找到
}
关键点是:一定要拿返回值和 end() 比较,不要直接解引用,也不要用 if (it) 判断(迭代器没有这种真假语义)。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
int main() {
// ———- 1. vector<int> 基础查找 ———-
std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};
auto it = std::find(v.begin(), v.end(), 5);
if (it != v.end()) {
std::cout << "[1] found 5 at index "
<< std::distance(v.begin(), it) << '\\n';
}
// ———- 2. 找不到的情况 ———-
auto it2 = std::find(v.begin(), v.end(), 42);
if (it2 == v.end()) {
std::cout << "[2] 42 not found\\n";
}
// ———- 3. 返回的是第一个匹配 ———-
std::vector<int> dup{1, 2, 2, 3, 2};
auto it3 = std::find(dup.begin(), dup.end(), 2);
std::cout << "[3] first 2 at index "
<< std::distance(dup.begin(), it3) << '\\n';
// ———- 4. 在 string 里找字符 ———-
std::string s = "hello world";
auto it4 = std::find(s.begin(), s.end(), 'w');
if (it4 != s.end()) {
std::cout << "[4] found 'w' at position "
<< (it4 – s.begin()) << '\\n';
}
// ———- 5. 自定义类型,需要 operator== ———-
std::vector<Person> people{
{"Alice", 30}, {"Bob", 25}, {"Carol", 35}
};
auto it5 = std::find(people.begin(), people.end(), Person{"Bob", 25});
if (it5 != people.end()) {
std::cout << "[5] found " << it5->name
<< ", age " << it5->age << '\\n';
}
// ———- 6. C++20 ranges 版本 ———-
#if __cplusplus >= 202002L
auto it6 = std::ranges::find(v, 9);
if (it6 != v.end()) {
std::cout << "[6] ranges::find found 9 at index "
<< std::distance(v.begin(), it6) << '\\n';
}
#endif
return 0;
}




实现100%通过率-171主机测评](https://www.171host.com/wp-content/uploads/2026/10/20261026191216-6adfa61015a7f-220x80.gif)
