内容
1.结构体概念
2.嵌套结构体的定义
3.结构体指针的定义
4.结构体数组的定义
5.结构体做函数参数(值传递、地址传递)
6.*英雄结构体+冒泡法——对英雄结构体里属性-年龄升序排列,最后打印输出
—————————————————————————————————————
*1.结构体概念
作用:允许用户储存不同类型的数据
语法:struct 结构体名 {结构体成员列表};
//创建学生结构体
struct student {
string name;
int age;
int score;
};
创建结构体变量的方式:
- struct 结构体名 变量名;
- struct 结构体名 变量名 = {成员1值,成员2值,…};
- 定义结构体时顺便创建变量;
例:
struct student{
string name;
int age;
int score;
}s3;//定义结构体的时候顺便定义一个结构体变量s3
int main()
{
//三种定义结构体变量的方法
struct student s1;
struct student s2={"张三",20,90};
s3.name="王五";
}
*2.嵌套结构体的定义
作用:一个结构体是另一个结构体的成员
struct student{
string Sname;
int Sage;
int Sscore;
};
struct teacher{
int id;
string Tname;
int Tage;
struct student Ts; //老师的结构体嵌套学生结构体,表示该老师所带的学生
};
*3.结构体指针的定义
作用:通过指针访问结构体中成员的属性
通过:结构体指针变量->成员属性 进行访问和修改
//通过*1中的方法先定义一个学生结构体变量
struct student s1;
struct student *p;
p=&s1; //或者直接定义为 struct student *p = &s1;
p->name="张三";
.... //通过指针对变量s1的成员属性(姓名、姓名、成绩)分别进行赋值
cout<<p->name<<s1.name<<endl; //输出结果一样
*4.结构体数组的定义
作用:可以批量定义多个结构体变量,存储在数组中,类型都为结构体
语法:struct 结构体名 数组名(数组定义方法有三种,具体可以查看如下链接)
数组定义(C++练习3)跳转链接
struct student Sarray[]={{"张山",20,90},{"王五",21,89}};
*5.结构体做函数参数
令结构体作为函数形参,函数调用时,结构体变量作为函数实参,实现对结构体变量的操作。
#include<iostream>
using namespace std;
#include<string>
struct student{
string name;
int age;
int score;
};
void printf01(student Stu) //值传递打印函数
{
Stu.age=19;
cout<<"值传递输出:"<<endl;
cout<<Stu.name<<"\t"<<Stu.age<<"\t"<<Stu.score<<endl;
}
void printf02(student * Stu) //地址传递打印函数
{
Stu->age=22;
cout<<"地址传递输出:"<<endl;
cout<<Stu->name<<"\t"<<Stu->age<<"\t"<<Stu->score<<endl;
}
int main()//主函数,程序入口
{
struct student stu={"张三",20,90};
struct student *p=&stu;
cout<<"实参数据为:"<<endl;
cout<<p->name<<"\t"<<p->age<<"\t"<<p->score<<endl;
printf01(stu);
cout<<"实参数据为:"<<endl;
cout<<p->name<<"\t"<<p->age<<"\t"<<p->score<<endl;
printf02(&stu);
cout<<"实参数据为:"<<endl;
cout<<p->name<<"\t"<<p->age<<"\t"<<p->score<<endl;
system("pause");
return 0;
}
结果为:
结论为:调用函数时,值传递实参不会随着形参的改变而改变;地址传递实参会随着形参改变而改变。
*6.英雄结构体输出
(1)创建一个英雄的结构体
(2)创建王者英雄的结构体变量
(3)对王者英雄的年龄进行冒泡排序
(4)进行英雄打印输出
#include<iostream>
using namespace std;
#include<string>
//创建一个英雄的结构体和英雄结构体数组,并利用冒泡排序法对年龄进行升序排列,并打印英雄列表
struct hero //创建一个英雄结构体
{
string name;
int age;
string sex;
};
//利用冒泡排序对英雄结构体中英雄的年龄升序排列
void bubbleSort(struct hero heroArray[],int len)
{
struct hero temp ;
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)
{
temp = heroArray[j];
heroArray[j]=heroArray[j+1];
heroArray[j+1]=temp;
}
}
}
}
//打印输出英雄列表
void printfHero(struct hero heroArray[],int len)
{
for(int i=0;i<len;i++)
{
cout<<heroArray[i].name<<"\t"<<heroArray[i].age<<"\t"<<heroArray[i].sex<<endl;
}
}
//主函数,程序入口
int main()
{
struct hero heroarray[]=
{
{"小乔",18,"女"},
{"周瑜",20,"男"},
{"李白",22,"男"},
{"王昭君",19,"女"}
};
int len = sizeof(heroarray)/sizeof(heroarray[0]);
//cout<<len<<endl;
bubbleSort(heroarray,len);
printfHero(heroarray,len);
system("pause");
return 0;
}
结果: