结构体数组
用途:将自定义的结构体放入数组方便维护
语法:struct 结构体名称 数组名称[元素个数] = {{数据,数据},{数据,数据}}
定义一个数组存放结构体:
#include <iostream>
#include <string>
using namespace std;
struct stu
{
string name;
int age;
int scores;
};
int main()
{
struct stu class1[] = { {"张三",18,100},{"李四",19,101},{"王五",20,110} };
system("pause");
return 0;
}
当然,也可以遍历打印:
#include <iostream>
#include <string>
using namespace std;
struct stu
{
string name;
int age;
int scores;
};
int main()
{
struct stu class1[] = { {"张三",18,100},{"李四",19,101},{"王五",20,110} };
int len(sizeof(class1) / sizeof(class1[0]));
for (int i = 0; i < len;i++)
{
cout << "name " << class1[i].name << "\tage " << class1[i].age << "\tscores " << class1[i].scores << endl;
}
system("pause");
return 0;
}
运行结果:(环境:Windows11 (arm/Apple M VM)/Visual Studio 2022/Debug/arm64)
name 张三 age 18 scores 100
name 李四 age 19 scores 101
name 王五 age 20 scores 110
请按任意键继续. . .
当然也可以修改(和数组一样咯)
class1[2].name = "赵六";
那么试试?(环境:Windows11 (arm/Apple M VM)/Visual Studio 2022/Debug/arm64)
name 张三 age 18 scores 100
name 李四 age 19 scores 101
name 赵六 age 20 scores 110
请按任意键继续. . .
:-)