当前位置:首页 C++ > 正文

c++结构体vector遍历

作者:野牛程序员:2023-07-31 20:42:03 C++阅读 2490

在 C++ 中,遍历存储结构体的 vector 可以使用多种方法,包括使用传统的 for 循环、范围-based for 循环和迭代器。以下是这些方法的示例:

假设有一个 Person 结构体:

#include <iostream>
#include <vector>

struct Person {
    std::string name;
    int age;
    std::string occupation;
};
  1. 使用传统的 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"}
    };

    // 使用传统的 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;
}
  1. 使用范围-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;
}
  1. 使用迭代器遍历:

#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 循环是最简洁和直观的遍历方法。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击