findindex使用案例
时间: 2023-07-22 08:01:02 浏览: 47
当使用C++编程语言时,可以使用`std::find`函数来查找容器中某个元素的索引。以下是一个使用案例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
int target = 30;
auto it = std::find(numbers.begin(), numbers.end(), target);
if (it != numbers.end()) {
int index = std::distance(numbers.begin(), it);
std::cout << "Element " << target << " found at index " << index << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
```
在上述代码中,我们定义了一个整数向量`numbers`并初始化了一些值。然后,我们使用`std::find`函数在容器中查找值为`target`的元素。如果找到了该元素,我们使用`std::distance`函数计算出该元素在容器中的索引,并将其打印出来。如果没有找到该元素,则输出"Element not found"。
运行上述代码,输出将是:
```
Element 30 found at index 2
```
这表明值为30的元素在向量中的索引为2。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)