从基础到进阶:C++ 中 find 函数的全方位解析
在 C++ 里,find
函数可用于在容器内查找特定值的首个出现位置。C++ 的标准库提供了多种find
相关功能,下面为你介绍主要的几种。
1. std::find
(定义于<algorithm>
头文件)
这个函数适用于所有遵循迭代器模式的容器,像vector
、list
、array
等。
cpp
#include <algorithm>
#include <vector>
#include <iostream>int main() {std::vector<int> numbers = {10, 20, 30, 40, 50};// 查找值为30的元素auto it = std::find(numbers.begin(), numbers.end(), 30);if (it != numbers.end()) {std::cout << "找到了元素: " << *it << std::endl;std::cout << "位置索引: " << std::distance(numbers.begin(), it) << std::endl;} else {std::cout << "未找到指定元素" << std::endl;}return 0;
}
关键要点:
- 函数的返回值是一个迭代器,若找到了目标元素,迭代器指向该元素;若没找到,则指向容器的末尾(
end()
)。 - 时间复杂度为 O (n)。
2. std::find_if
(定义于<algorithm>
头文件)
当你需要依据自定义条件查找元素时,可以使用这个函数。
cpp
#include <algorithm>
#include <vector>
#include <iostream>bool isEven(int num) {return num % 2 == 0;
}int main() {std::vector<int> numbers = {1, 3, 4, 5, 7};// 查找第一个偶数auto it = std::find_if(numbers.begin(), numbers.end(), isEven);if (it != numbers.end()) {std::cout << "第一个偶数是: " << *it << std::endl;} else {std::cout << "没找到偶数" << std::endl;}return 0;
}
关键要点:
- 第三个参数是一个一元谓词(可以是函数、函数对象或者 lambda 表达式),用于定义查找条件。
3. 关联容器的find
成员函数(如std::map
、std::set
)
关联容器自身就提供了find
成员函数,其时间复杂度为 O (log n)。
cpp
#include <map>
#include <iostream>int main() {std::map<std::string, int> ages = {{"Alice", 25},{"Bob", 30},{"Charlie", 35}};// 查找Bob的年龄auto it = ages.find("Bob");if (it != ages.end()) {std::cout << "Bob的年龄是: " << it->second << std::endl;} else {std::cout << "未找到Bob的年龄信息" << std::endl;}return 0;
}
关键要点:
- 关联容器会依据键的有序性来快速查找元素。
- 返回的迭代器是一个键值对(如
std::pair<const Key, T>
)。
4. 字符串的find
成员函数(std::string
)
该函数用于在字符串里查找子串或者字符。
cpp
#include <string>
#include <iostream>int main() {std::string text = "Hello, world!";// 查找子串"world"size_t pos = text.find("world");if (pos != std::string::npos) {std::cout << "找到了子串,位置在: " << pos << std::endl;} else {std::cout << "未找到子串" << std::endl;}return 0;
}
关键要点:
- 返回值的类型是
size_t
,代表子串的起始位置。
- 如果没有找到,返回std::string::npos
。
总结
函数 | 适用场景 | 返回类型 | 时间复杂度 |
---|---|---|---|
std::find | 通用容器的查找 | 迭代器 | O(n) |
std::find_if | 按自定义条件查找 | 迭代器 | O(n) |
关联容器的find() | 在map 、set 等容器中按键查找 | 迭代器 | O(log n) |
字符串的find() | 在字符串中查找子串或字符 | size_t (位置) | O(n) |
关于上述的几个函数你看明白了吗,如果有不明白的地方,欢迎及时咨询,有问必答系列...