- 1.结构体嵌套结构体
struct student
{
string name;
int age;
int score;
};
struct teacher
{
int number;
string name;
int age;
struct student stu;
};
void print_struct(struct student* p) {
cout << "学生姓名:" << p->name << endl
<< "学生分数:" << p->score << endl;
}
teacher t;
t.name="老王";
t.age = 28;
t.number = 1;
t.stu.name = "小王";
t.stu.age = 10;
t.stu.score = 100;
cout << "老师的姓名:" << t.name << endl
<< "老师的年龄: " << t.age << endl
<< "老师的学生: " << t.stu.name << endl;
print_struct(&t.stu);//地址传入
- 2.获取字符串的第几个字符
#include <string>
string nameSeed="ABCDE";
void allocate(struct Teacher tArray[],int len){
for(int i =0;i<len;i++){
tArray[i].name = "Teacher_";
tArray[i].name += nameSeed[i];//直接字符串nameSeed[i],就行
}
}
- 3.案例:根据结构体的年龄,使用冒泡排序:
#include <iostream>
using namespace std;
#include <string>
struct Hero
{
string name;
int age;
string sex;
};
void sort_hero(struct Hero hero[],int len) {
struct Hero h1;
for (int i = 0;i<len-1;i++) {
for (int j = 0;j<len-1-i;j++) {
if (hero[j].age>hero[j+1].age) {
h1 = hero[j];
hero[j] = hero[j + 1];
hero[j + 1] = h1;
}
}
}
}
void print_info(struct Hero hero[], int len) {
for (int i = 0;i<len;i++) {
cout << "英雄人物:" << hero[i].name
<< " 英雄年龄:" << hero[i].age
<< " 英雄性别:" << hero[i].sex << endl;
}
}
int main() {
struct Hero hero[5] = {
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
int len = sizeof(hero) / sizeof(hero[0]);
sort_hero(hero, len);
print_info(hero,len);
system("pause");
return 0;
}
- 4.c++清屏操作
system("pause");
system("cls");