从熟练Python到入门学习C++(record 6)
基础之基础之最后一节-结构体
1.结构体的定义
结构体相对于自定义的一种新的变量类型。
四种定义方式,推荐第一种;第四种适合大量定义,也适合查找;
#include <iostream>
using namespace std;
#include <string.h>struct Student
{string name;int age;float score;
}s3;void prinf(Student s)
{cout << s.name << " | " << s.age << " | " << s.score << endl;
}int main()
{Student s1;s1.name = "niuniu";s1.age = 18;s1.score = 96;prinf(s1);Student s2 = { "zhangsan", 92, 30 };prinf(s2);s3.name = "lisi";s3.age = 13;s3.score = 31;prinf(s3);//shuzuStudent arr[3] = {{"zhangsan", 31,55},{"lisi", 41, 42},{"wangwu", 32,44}};for (int i = 0; i < 3; ++i){prinf(arr[i]);};return 0;}
2.结构体指针
和其他类型的指针一致;需要注意的是,如果s是结构体的指针,不仅可以使用(*s).name还可以使用s->name访问结构体的属性;
#include <iostream>
using namespace std;
#include <string.h>struct Student
{string name;int age;float score;
}s3;void prinf(Student* s)
{cout << s->name << " | " << s->age << " | " << s->score << endl;
}int main()
{Student s1;s1.name = "niuniu";s1.age = 18;s1.score = 96;prinf(&s1);Student s2 = { "zhangsan", 92, 30 };prinf(&s2);s3.name = "lisi";s3.age = 13;s3.score = 31;prinf(&s3);//shuzuStudent arr[3] = {{"zhangsan", 31,55},{"lisi", 41, 42},{"wangwu", 32,44}};for (int i = 0; i < 3; ++i){prinf(&arr[i]);};return 0;}
3.结构体嵌套结构体
类似于函数中包含函数;
#include <iostream>
using namespace std;
#include <string.h>struct teacher
{int id;string name;int age;student std;
};struct student
{string name;int age;int score;
};
结果报错,因为需要把student放在前面!!!
4.案例
给三国英雄排序;使用结构体,指针
#include <iostream>
#include <string.h>
using namespace std;struct hero
{string name;int age;string gender;
};void prf(hero arr[5])
{for (int i = 0; i < 5; i++){cout << arr[i].name << " | " << arr[i].age << " | " << arr[i].gender << endl;}
}void sort(hero arr[5], const int nums)
{for (int i = 0; i < nums; i++){int counts = nums;for (int j = 0; j < nums - i - 1; j++){if (arr[j].age > arr[j + 1].age){hero tmp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = tmp;counts--;}}}
}int main()
{hero arr[5] = {{"liubei",22,"nan"},{"guanyu", 22, "nan"},{"zhangfei", 20, "nan"},{"zhaoyun", 21, "nan"},{"diaochan", 19, "nv"}};sort(arr, 5);prf(arr);return 0;}
总结一下:
1.对于python来说,数组传入函数时,相当于传入c++指针,因为函数中改变数组中的值,外部的数组也会改变;所以不想改变的时候,需要使用deep.copy。
2.对于c++来说,不仅数组传入相对于指针,对于整型、实型及结构体,只要使用&a,把a的指针传入函数,在函数中修改后,外部的值也会改变。
3.对于c++的数组来说,就算不使用*p,arr本身也是地址。所以在函数中对于传入的arr来说,不需要使用指针,也能干指针的活;