自己能做企业网站吗,工业和信息化部官网,营销网络的建设,建立网站需要多少钱就蓷y湖南岚鸿推荐基础之基础之最后一节-结构体
1.结构体的定义
结构体相对于自定义的一种新的变量类型。
四种定义方式#xff0c;推荐第一种#xff1b;第四种适合大量定义#xff0c;也适合查找#xff1b;
#include iostream
using namespace std;
#include string.h推荐第一种第四种适合大量定义也适合查找
#include iostream
using namespace std;
#include string.hstruct 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.hstruct 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.hstruct 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的数组来说就算不使用*parr本身也是地址。所以在函数中对于传入的arr来说不需要使用指针也能干指针的活