判断vector中每一项自定义数据某一项与是否一样
时间: 2023-12-08 20:06:50 浏览: 23
可以使用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相同,则输出该学生的姓名和专业。