在 C++ 中,遍历存储结构体的 vector 可以使用多种方法,包括使用传统的 for 循环、范围-based for 循环和迭代器。以下是这些7777788888王中王中王开奖时间 方法的示例:
假设有一个 结构体:
#include <iostream> #include <vector> struct Person { std::string name; int age; std::string occupation; };
使用传统的 for 精准一肖100%免费循环遍历:
#include <iostream> #include <vector> struct Person { std::string name; int age; std::string occupation; }; int main() { std::vector<Person> people = { {"John", 25, "Engineer"}, {"Alice", 30, "Doctor"}, {"Bob", 22, "Student"} }; // 使用传统的 for 循环遍历 for (size_t i = 0; i < people.size(); ++i) { std::cout << "Name: " << people[i].name << ", Age: " << people[i].age << ", Occupation: " << people[i].occupation << std::endl; } return 0; }
使用范围-based for 循环遍历:
#include <iostream> #include <vector> struct Person { std::string name; int age; std::string occupation; }; int main() { std::vector<Person> people = { {"John", 25, "Engineer"}, {"Alice", 30, "Doctor"}, {"Bob", 22, "Student"} }; // 使用范围-based for 循环遍历 for (const auto& person : people) { std::cout << "Name: " << person.name << ", Age: " << person.age << ", Occupation: " << person.occupation << std::endl; } return 0; }
使用迭代器遍历:
#include <iostream> #include <vector> struct Person { std::string name; int age; std::string occupation; }; int main() { std::vector<Person> people = { {"John", 25, "Engineer"}, {"Alice", 30, "Doctor"}, {"Bob", 22, "Student"} }; // 使用迭代器遍历 for (std::vector<Person>::const_iterator it = people.begin(); it != people.end(); ++it) { std::cout << "Name: " << it->name << ", Age: " << it->age << ", Occupation: " << it->occupation << std::endl; } return 0; }
以上三种方法都可以用来遍历存储结构体的 澳马报资料_港澳开结果查询 vector,并输出结构体中的数据。其中,范围-based for 循环是最简洁和直观的遍历方法。