C++find函数详解
时间: 2023-11-15 21:05:02 浏览: 166
`find()` 函数是 C++ STL 中的算法之一,用于在一个容器中查找指定的元素,并返回第一次出现该元素的位置。如果该元素不存在,则返回容器的 `end()` 迭代器。
`find()` 函数可以用于查找数组、向量、列表、集合、映射等容器中的元素。它的语法如下:
```c++
iterator find (iterator first, iterator last, const T& val);
```
其中,`first` 和 `last` 分别是容器中查找范围的起始和结束位置,`val` 是要查找的元素。返回值是一个迭代器,指向第一次出现 `val` 的位置。如果容器中不存在 `val`,则返回 `last` 迭代器。
下面是一个示例程序,演示如何使用 `find()` 函数在向量中查找一个元素:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vec{ 1, 2, 3, 4, 5 };
auto it = find(vec.begin(), vec.end(), 3);
if (it != vec.end())
{
cout << "Found at index: " << distance(vec.begin(), it) << endl;
}
else
{
cout << "Not Found!" << endl;
}
return 0;
}
```
上述程序将输出:Found at index: 2,因为 3 在向量中的位置是 2。
需要注意的是,对于有序容器(如 set、map),可以使用 `lower_bound()` 和 `upper_bound()` 函数来查找元素。这两个函数返回的是迭代器,指向第一个大于等于(或大于)指定元素的位置。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)