结构体基本概念
结构体定义和使用
在C++种,在创建变量是,struct关键字可以省略,结构体定义时不可以省略
结构体数组
结构体指针
结构体嵌套结构体
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
struct teacher
{
int id;
string name;
struct student std;
};
int main()
{
teacher t;
t.id = 10000;
t.name = "韩老师";
t.std.name = "王学生";
t.std.age = 18;
t.std.score = 100;
cout << "老师的编号为: " << t.id << endl
<< "老师的姓名为: " << t.name << endl
<< "所带学生的姓名为: " << t.std.name << endl
<< "所带学生的年龄为: " << t.std.age << endl
<< "所带学生的成绩为: " << t.std.score << endl;
system("pause");
return 0;
}
结构体做函数参数
结构体中const的使用场景
结构体案例
案例一
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct student
{
string name;
int score;
};
struct teacher
{
string name;
student stu[5];
};
int main()
{
teacher ter[3];
int i = 0;
int j = 0;
//赋值
for (i = 0; i < 3; i++)
{
cout << "请输入第" << i+1 << "个老师的姓名:" ;
cin >> ter[i].name;
for (j = 0; j < 5; j++)
{
cout << "请输入第" << j + 1 << "个学生的姓名:" ;
cin >> ter[i].stu[j].name;
cout << "请输入第" << j + 1 << "个学生的分数:" ;
cin >> ter[i].stu[j].score;
}
}
//输出
for (int i = 0; i < 3; i++)
{
cout << "第" << i + 1 << "个老师的姓名为:" << ter[i].name << endl;
for (j = 0; j < 5; j++)
{
cout << " " << "第" << j + 1 << "个学生的姓名为:" << ter[i].stu[j].name << endl;
cout << " " << "第" << j + 1 << "个学生的成绩为:" << ter[i].stu[j].score << endl;
}
}
system("pause");
return 0;
}
案例二
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct Hero
{
string name;
int age;
string sex;
};
int main()
{
Hero h[5] = {
{"刘备",23,"男"},
{"关于",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
int i = 0;
int j = 0;
//冒泡排序
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4 - i; j++)
{
if ((h[j].age) > (h[j + 1].age))
{
Hero temp = h[j];
h[j] = h[j + 1];
h[j + 1] = temp;
}
}
}
//输出
for (i = 0; i < 5; i++)
{
cout << h[i].name << "\t" << h[i].age << "\t" << h[i].sex << endl;
}
system("pause");
return 0;
}
string的加法运算
直接在后面追加字符
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
int main()
{
string name = "abd";
name += "cd";//可追加任意长度
cout << name << endl;//abdcd
system("pause");
return 0;
}
随机数的生成
包含头文件
#include<ctime>
srand((unsigned int)time(NULL));
cout<<rand();