C++中的结构体数组是一种复合数据类型,它是由若干个结构体变量组成的一个数组。它的定义方法和普通数组的定义方法类似,只是在变量类型前面加上struct关键字,如:
struct student
{
char name[20];
int age;
char sex[10];
int score;
};
struct student stu[10];
上面的代码定义了一个结构体数组,它由10个student结构体变量组成。
常见操作方法
1. 赋值:结构体数组的赋值和普通数组的赋值类似,只是需要将每个结构体变量的值都赋值一次,如:
struct student stu[10] =
{
{"Tom", 18, "male", 90},
{"Jack", 20, "male", 80},
{"Lily", 19, "female", 95},
{"Lucy", 19, "female", 85},
{"Marry", 20, "female", 92},
{"John", 18, "male", 88},
{"David", 20, "male", 75},
{"Amy", 18, "female", 93},
{"Bob", 19, "male", 79},
{"Peter", 20, "male", 83}
};
2. 取值:取值时,只需要指定结构体数组的下标,就可以取到数组中指定位置的结构体变量,如:
struct student stu1 = stu[0];
3. 遍历:结构体数组的遍历和普通数组的遍历类似,只是需要用一个循环变量来遍历每个结构体变量,如:
for(int i=0;i<10;i++)
{
printf("name: %s, age: %d, sex: %s, score: %d\n", stu[i].name, stu[i].age, stu[i].sex, stu[i].score);
}
4. 排序:结构体数组的排序和普通数组的排序类似,只是需要指定排序的依据,如:
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(stu[i].score > stu[j].score)
{
struct student temp = stu[i];
stu[i] = stu[j];
stu[j] = temp;
}
}
}
上面的代码是对结构体数组按照成绩进行升序排序的代码,可以根据需要改变排序的依据。