vector中find函数用法
时间: 2023-10-10 13:06:09 浏览: 171
vector中的find函数用于在vector中查找特定的元素。该函数返回一个迭代器,指向第一个匹配到的元素,如果未找到则返回指向vector尾部的迭代器。以下是find函数在vector中的用法示例:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> arr;
arr.push_back(1);
arr.push_back(5);
arr.push_back(12);
arr.push_back(7);
arr.push_back(6);
arr.push_back(4);
// 输出一下vector
for (int i = 0; i < arr.size(); i++) {
std::cout << arr[i << " ";
}
std::cout << std::endl;
// 使用find()对vector进行查找
std::vector<int>::iterator it;
it = std::find(arr.begin(), arr.end(), 7);
if (it != arr.end()) {
// 若返回的迭代器不指向end,说明查到了元素
std::cout << "输出查到的元素:" << *it << std::endl;
std::cout << "输出查到的元素的下标:" << it - arr.begin();
} else {
std::cout << "查找失败";
}
return 0;
}
```
在上述代码中,首先我们定义了一个vector并向其中添加了一些元素。然后,我们通过使用find函数在vector中查找值为7的元素,并将返回的迭代器存储在it变量中。如果找到了匹配的元素,我们将输出它的值和下标;否则,我们将输出"查找失败"。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [C++ find()函数对vector的查找](https://blog.csdn.net/weixin_46585382/article/details/125218996)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [C++在成员函数中使用STL的find_if函数实例](https://download.csdn.net/download/weixin_38590355/14913800)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [C++ find函数详解](https://blog.csdn.net/weixin_46585382/article/details/125218856)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文