结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
结构体数组 作用:将自定义的结构体放入到数组中方便维护
struct 结构体名 数组名[元素个数]={ {} , {} ,...{} }
结构体指针 利用->可以通过结构体指针访问结构体属性
通过指针指向结构体变量
结构体嵌套结构体 结构体中的成员可以是另一个结构体
结构体做函数参数
值传递
地址传递
结构体中const使用场景 只能读不能写
将函数中的形参改为指针,可以减少内存空间,而且不会复制新的副本出来
加入const之后,一旦有修改的操作就会报错,可以防止误操作
//结构体案例1
#include <iostream>
#include <memory>
#include <string>
#include <ctime>
using namespace std;
struct student{
string sName;
int score;
};
struct Teacher{
string tName;
struct student sArray[5];
};
//给老师和学生赋值的函数
void allocateSpace(struct Teacher tArray[],int len){
string nameSeed ="ABCDE";
for (int i=0; i<len; i++) {
tArray[i].tName="Teacher_";
tArray[i].tName+=nameSeed[i];
for (int j=0; j<5; j++) {
tArray[i].sArray[j].sName="Student_";
tArray[i].sArray[j].sName+=nameSeed[j];
int random =rand()%61+40;//40~100的随机数
tArray[i].sArray[j].score=random;
}
}
}
//打印所有信息
void printInfo(struct Teacher tArray[],int len){
for (int i=0; i<len; i++) {
cout<<"老师姓名 "<<tArray[i].tName<<endl;
for (int j=0; j<5; j++) {
cout<<"\t学生姓名 "<<tArray[i].sArray[j].sName<<" 考试分数: "<<tArray[i].sArray[j].score<<endl;
}
}
}
int main() {
//随机数种子
srand((unsigned int)time(NULL));
struct Teacher tArray[3];
int len=sizeof(tArray)/sizeof(tArray[0]);
allocateSpace(tArray, len);
printInfo(tArray,len);
}
//结构体案例2
#include <iostream>
#include <string>
using namespace std;
struct Hero{
string name;
int age;
string sex;
};
void bubbleSort(struct Hero heroArray[],int len){
for (int i=0; i<len-1; i++) {
for (int j=0; j<len-i-1; j++) {
if (heroArray[j].age>heroArray[j+1].age) {
struct Hero tmp=heroArray[j];
heroArray[j]=heroArray[j+1];
heroArray[j+1]=tmp;
}
}
}
}
void printHero(struct Hero heroArray[],int len){
for (int i=0; i<len; i++) {
cout<<"姓名: "<<heroArray[i].name<<"年龄:"<<heroArray[i].age<<"性别:"<<heroArray[i].sex<<endl;
}
}
int main(){
struct Hero heroArray[]={
{"刘备",23,"male"},
{"关羽",22,"male"},
{"张飞",20,"male"},
{"赵云",21,"male"},
{"貂蝉",19,"female"},
};
int len =sizeof(heroArray)/sizeof(heroArray[0]);
bubbleSort(heroArray,len);
printHero(heroArray, len);
}