怎么去判断一个元素是否在vector中
时间: 2023-12-03 19:45:29 浏览: 63
可以使用`std::find()`函数来判断一个元素是否在`vector`中。该函数在`<algorithm>`头文件中定义。使用该函数需要提供要查找的元素所在的范围(即`vector`的起始和结束迭代器),以及要查找的元素值。如果找到了该元素,函数将返回指向该元素的迭代器;否则,函数将返回指向`vector`的末尾迭代器。
以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << target << " is found in the vector." << std::endl;
} else {
std::cout << target << " is not found in the vector." << std::endl;
}
target = 6;
it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << target << " is found in the vector." << std::endl;
} else {
std::cout << target << " is not found in the vector." << std::endl;
}
return 0;
}
```
输出:
```
3 is found in the vector.
6 is not found in the vector.
```
上述代码中,我们先创建了一个`vector`,然后分别查找其中的元素3和6。通过`std::find()`函数和`if`语句的判断,最终输出了查询结果。