判断一个值是否在Vector中是否包含某个值
时间: 2024-05-11 13:17:57 浏览: 14
可以使用std::find()函数来判断一个值是否在vector中:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int n = 3;
auto it = std::find(vec.begin(), vec.end(), n);
if (it != vec.end()) {
std::cout << "Found " << n << " in vector" << std::endl;
} else {
std::cout << "Did not find " << n << " in vector" << std::endl;
}
return 0;
}
```
这里使用std::find()函数来查找值为3的元素是否在vector中,如果找到了就输出“Found 3 in vector”,否则输出“Did not find 3 in vector”。
相关问题
用c++编写一个在vector容器中判断某个数是否存在的代码
以下是用 C++ 编写一个在 vector 容器中判断某个数是否存在的代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
int target = 3;
if (find(nums.begin(), nums.end(), target) != nums.end()) {
cout << "Target exists in the vector." << endl;
} else {
cout << "Target does not exist in the vector." << endl;
}
return 0;
}
```
这段代码中,我们首先定义了一个 vector 容器 nums,其中包含了一些整数。然后我们定义了一个目标数 target,我们需要判断这个数是否存在于 nums 中。
我们使用了 C++ 标准库中的 find 函数来查找 target 是否存在于 nums 中。如果 find 函数返回的迭代器不等于 nums.end(),则说明 target 存在于 nums 中,否则说明 target 不存在于 nums 中。
注意:这段代码只是一个示例,实际使用时需要根据具体情况进行修改。
判断vector中每一项自定义数据某一项与是否一样
可以使用for循环遍历vector中的每一项,然后通过自定义数据类型的某一项与给定的值进行比较。如果相同,则进行相应的操作,否则继续遍历下一项。以下是一个示例代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct Student {
string name;
int age;
string major;
};
int main() {
vector<Student> students = {{"Tom", 20, "Computer Science"}, {"Mary", 19, "Mathematics"}, {"John", 21, "Physics"}};
string major_to_find = "Mathematics";
for (auto student : students) {
if (student.major == major_to_find) {
cout << student.name << " is majoring in " << major_to_find << endl;
}
}
return 0;
}
```
在上面的示例中,我们定义了一个名为Student的结构体,包含了三个成员变量:name、age和major。然后我们创建了一个vector,存储了三个Student对象。接着,我们定义了一个字符串变量major_to_find,用于表示要查找的专业。在for循环中,我们遍历了vector中的每一个Student对象,如果某个对象的major与major_to_find相同,则输出该学生的姓名和专业。