vector中查找某个元素
时间: 2023-10-02 18:05:53 浏览: 73
要在vector中查找某个元素,可以使用find函数。find函数接受两个参数,第一个参数是要查找的元素的起始位置,第二个参数是要查找的元素的结束位置。如果找到了该元素,则返回指向该元素的迭代器;如果未找到,则返回结束位置的迭代器。以下是一个示例代码:
```cpp
vector<int> nums = {1, 2, 3, 4, 5};
int target = 3;
vector<int>::iterator it = find(nums.begin(), nums.end(), target);
if (it != nums.end()) {
cout << "元素 " << target << " 在vector中找到了" << endl;
} else {
cout << "元素 " << target << " 在vector中未找到" << endl;
}
```
此代码将在vector中查找元素3,并输出"元素 3 在vector中找到了"的结果。注意,要使用find函数,需要包含<algorithm>头文件。
相关问题
在c++语言中如何在vector中查找某个元素
在C++中,可以使用`std::find`算法函数在vector中查找某个元素。使用这个函数需要包含头文件`<algorithm>`。
下面是一个示例代码,演示如何在vector中查找一个字符串元素:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> vec = {"apple", "banana", "orange", "pear"};
// 在vector中查找元素"orange"
auto it = std::find(vec.begin(), vec.end(), "orange");
// 输出查找结果
if (it != vec.end()) {
std::cout << "元素找到,位置为:" << it - vec.begin() << std::endl;
} else {
std::cout << "元素未找到" << std::endl;
}
return 0;
}
```
输出结果为:
```
元素找到,位置为:2
```
在上面的代码中,`std::find(vec.begin(), vec.end(), "orange")`函数返回一个指向要查找元素的迭代器。如果要查找的元素不存在,返回的迭代器等于`vec.end()`,可以用来判断是否找到元素。
C++查找vector是否有某个元素
在 C++ 中,你可以使用 std::find 函数来查找 vector 中是否存在某个元素。该函数需要传入三个参数,第一个参数为要查找的 vector,第二个参数为要查找的元素,第三个参数为 vector 的起始位置。如果查找成功,该函数会返回指向该元素的迭代器,否则返回 vector::end()。
具体使用方法如下:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
int search_num = 3;
auto it = std::find(vec.begin(), vec.end(), search_num);
if (it != vec.end()) {
std::cout << "The vector contains " << search_num << std::endl;
} else {
std::cout << "The vector does not contain " << search_num << std::endl;
}
return 0;
}
```
以上代码会输出 "The vector contains 3"。如果将 search_num 改为 6,则会输出 "The vector does not contain 6"。