结构体
廖家龙 用心听,不照做

结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

在结构体中可以定义另一个结构体作为成员

值传递传参的时候会耗费大量的内存空间,用地址传递可以减少内存空间,而且不会复制新的副本出来

结构体中用const来防止误操作:

—————————————

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#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-1-i;j++){
if(heroArray[j].age>heroArray[j+1].age){
struct Hero temp=heroArray[j];
heroArray[j]=heroArray[j+1];
heroArray[j+1]=temp;
}
}
}
}

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(int argc, char *argv[]) {

struct Hero heroArray[5]={
{“刘备”,23,”男”},
{“关羽”,22,”男”},
{“张飞”,20,”男”},
{“赵云”,21,”男”},
{“貂蝉”,19,”女”},
};

int len=sizeof(heroArray)/sizeof(heroArray[0]);

bubbleSort(heroArray,len);

printHero(heroArray,len);

}