find() 是一个 STL 函数,它位于
用法:
InputIterator find( InputIterator first, InputIterator last, const T& val);
其中,
InputIterator first
- 搜索范围开始的迭代器InputIterator last
- 到搜索范围结束的迭代器const T& val
- 要搜索的数据类型 T 的值什么是输入迭代器?
迭代器到我们找到搜索元素的范围的第一个位置。如果未找到搜索元素,则将迭代器返回到末尾
返回类型: bool
无论是否找到搜索元素,都使用上述语法搜索相应范围内的元素。
时间复杂度:线性时间,O(n)
之间的区别binary_search()和 find() 函数
范例1:当搜索到的元素被找到并且在搜索范围内只有一个实例时
- #include <bits/stdc++.h>
- using namespace std;
-
- int main()
- {
- vector<int> arr{ 1, 2, 3, 8, 4, 3 };
-
- int searching_element = 8;
- vector<int>::iterator it;
- //starting iterator of range= arr.begin()
- //end iterator of range =arr.end()
-
- it = find(arr.begin(), arr.end(), searching_element);
- if (it != arr.end())
- cout << searching_element << " is at position:" << it - arr.begin() << endl;
- else
- cout << searching_element << "not found";
-
- return 0;
- }
输出:
8 is at position:3
在上面的程序中,我们检查了搜索元素,发现它在3rd索引(0-索引)
范例2:当搜索到的元素被找到并且在搜索范围内有多个实例时
- #include <bits/stdc++.h>
- using namespace std;
-
- int main()
- {
- vector<int> arr{ 1, 2, 3, 8, 4, 3 };
-
- int searching_element = 3;
- vector<int>::iterator it;
- //starting iterator of range= arr.begin()
- //end iterator of range =arr.end()
-
- it = find(arr.begin(), arr.end(), searching_element);
- if (it != arr.end())
- cout << searching_element << " is at position:" << it - arr.begin() << endl;
- else
- cout << searching_element << "not found";
-
- return 0;
- }
输出:
3 is at position:2
在上面的例子中,我们在数组中搜索 3,该数组有两个实例,一个在位置索引 2,另一个在位置 5。由于 std::find()在找到搜索元素时停止搜索,因此它返回索引 2(检查我们如何找到它返回的迭代器的位置)。
范例3:当在搜索范围内未找到搜索元素时
- #include <bits/stdc++.h>
- using namespace std;
-
- int main()
- {
- vector<int> arr{ 1, 2, 3, 8, 4, 3 };
-
- int searching_element = 7;
- vector<int>::iterator it;
- //starting iterator of range= arr.begin()
- //end iterator of range =arr.end()
-
- it = find(arr.begin(), arr.end(), searching_element);
- if (it != arr.end())
- cout << searching_element << " is at position:" << it - arr.begin() << endl;
- else
- cout << searching_element << " not found";
-
- return 0;
- }
输出:
7 not found
在上述情况下,搜索元素不存在,这就是它返回 arr.end() 的原因,这意味着迭代器到范围的末尾。
好了, 以上是本文所有内容,希望对大家有所帮助,也希望大家对码农之家多多支持,你们的支持是我创作的动力!祝大家生活愉快!