在 C++ 中,不同的数据结构(如 int[]
、string
、set
、map
)的 find
方法或查找方式各有不同。下面是它们的具体实现方式和差异:
1. 数组(int[]
或 std::vector<int>
)
实现方式:
- 普通数组(C 风格) 没有
find
方法,需要用for
循环或者std::find
来查找。 std::vector<int>
可以使用std::find
,输入参数前两个为迭代器,表示查找范围的起始和结束,第三个参数为值,返回值为指向该值对应元素的迭代器。
示例:
#include <iostream>
#include <vector>
#include <algorithm> // std::find
int main() {
std::vector<int> arr = {
1, 2, 3, 4, 5};
auto it = std::find(arr.begin(), arr.end(), 3); // 查找3
if (it != arr.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
特点
- 时间复杂度:O(n),因为
std::find
线性搜索。 - 适用范围:适用于小规模数组或顺序存储的数据。
2. 字符串(std::string
)
实现方式:
- 使用
find
方法 查找子串的位置。 - 返回值:找到时返回索引,找不到返回
std::string::npos
。