c++ find
时间: 2023-07-12 07:21:29 浏览: 41
`std::find` 是C++ STL中的一个函数,用于在一个容器中查找指定的元素。它的语法如下:
```
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );
```
其中,`first` 和 `last` 是容器中用于查找的起始和结束迭代器,`value` 是要查找的元素。`find` 函数会从 `first` 开始一个个地遍历容器中的元素,如果找到了等于 `value` 的元素,就返回该元素的迭代器;否则返回 `last`。
例如,下面的代码演示了如何使用 `std::find` 在一个 `vector` 中查找指定的元素:
```c++
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
std::cout << "Found " << *it << " at position " << (it - v.begin()) << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Found 3 at position 2
```