温馨提示×

C++中如何定义和使用struct数组

c++
小樊
81
2024-09-10 19:23:41
栏目: 编程语言

在C++中,您可以像定义和使用其他类型的数组一样来定义和使用结构体(struct)数组。以下是一个简单的示例,说明如何定义和使用结构体数组:

  1. 首先,定义一个结构体类型。例如,我们定义一个表示人的结构体:
#include<iostream>
#include<string>

struct Person {
    std::string name;
    int age;
};
  1. 接下来,定义一个结构体数组。例如,我们定义一个包含3个Person对象的数组:
int main() {
    Person people[3];

    // 为数组中的每个元素分配值
    people[0] = {"Alice", 30};
    people[1] = {"Bob", 25};
    people[2] = {"Charlie", 22};

    // 输出数组中每个元素的信息
    for (int i = 0; i < 3; ++i) {
        std::cout << "Name: "<< people[i].name << ", Age: "<< people[i].age<< std::endl;
    }

    return 0;
}

这个程序首先定义了一个名为Person的结构体类型,然后创建了一个包含3个Person对象的数组。接着,我们为数组中的每个元素分配了一些值,并最后遍历数组并输出每个元素的信息。

注意,在C++中,您还可以使用std::vectorstd::array来处理结构体数组,这两者都提供了更多的功能和灵活性。例如,使用std::vector

#include<iostream>
#include<string>
#include<vector>

struct Person {
    std::string name;
    int age;
};

int main() {
    std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 22}};

    // 输出数组中每个元素的信息
    for (const auto &person : people) {
        std::cout << "Name: "<< person.name << ", Age: "<< person.age<< std::endl;
    }

    return 0;
}

在这个例子中,我们使用了std::vector来存储Person对象,并使用了范围for循环来遍历和输出数组中的每个元素。

0