一、std::find(最常用)

头文件

1
#include <algorithm>

原型

1
2
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value);

作用

在区间 [first, last) 中查找 第一个等于 value 的元素


1️⃣ 在 vector 中查找

1
2
3
4
5
6
7
8
9
vector<int> a = {1, 3, 5, 7};

auto it = find(a.begin(), a.end(), 5);

if (it != a.end()) {
cout << "找到了,下标 = " << it - a.begin() << endl;
} else {
cout << "没找到" << endl;
}

📌 关键点

  • 返回的是 迭代器
  • 没找到 → 返回 end()

2️⃣ 在数组中查找

1
2
3
4
5
6
7
8
int a[] = {10, 20, 30, 40};
int n = 4;

auto it = find(a, a + n, 30);

if (it != a + n) {
cout << "找到了,位置 = " << it - a << endl;
}

3️⃣ 在 string(字符层面)中用 std::find

1
2
3
4
5
6
7
string s = "hello";

auto it = find(s.begin(), s.end(), 'e');

if (it != s.end()) {
cout << "找到了,位置 = " << it - s.begin() << endl;
}

⚠️ 注意:
这是 algorithm 的 find,不是字符串成员函数。


二、string::find(字符串专用)

头文件

1
#include <string>

4️⃣ 查找子串(最常见)

1
2
3
4
5
6
7
string s = "hello world";

int pos = s.find("world");

if (pos != string::npos) {
cout << "起始位置 = " << pos << endl;
}

📌

  • 返回 下标
  • 找不到 → string::npos

5️⃣ 从指定位置开始找

1
2
3
4
string s = "ababab";

int pos = s.find("ab", 2); // 从下标 2 开始
cout << pos << endl; // 2

6️⃣ 查找字符

1
2
3
string s = "abcde";

int pos = s.find('c'); // 2

三、find vs string::find 对比(必会)

对比点 std::find string::find
头文件 <algorithm> <string>
返回值 迭代器 下标
适用对象 所有容器 string
未找到 end() string::npos

四、常见错误(很重要)

忘了判断是否找到

1
2
auto it = find(v.begin(), v.end(), x);
cout << *it; // ❌ 如果没找到会崩

✔️ 正确写法

1
2
3
if (it != v.end()) {
cout << *it;
}

混淆两个 find

1
2
string s = "abc";
auto it = find("a"); // ❌

✔️

1
2
s.find('a');        // string::find
find(s.begin(), s.end(), 'a'); // std::find

五、时间复杂度(竞赛要知道)

  • std::findO(n)(顺序查找)
  • string::find:通常 O(n)

⚠️ 若需要快速查找:

  • set / mapfind()O(log n)
  • unordered_map → 平均 O(1)

六、一句话总结

容器找元素用 std::find,字符串找子串用 string::find