结构体:不同数据类型的集合。
1 声明结构体
cpp
struct StructName {
type_1 member_1;
type_2 member_2;
...
type_n member_n;
};说明:
struct定义结构体的关键字。StructName和member遵循标识符的命名规则,建议结构体类型名(StructName)首字母大写。type是结构体成员的数据类型,它可以是任何类型,当然也包括其他结构体类型。- 结构体类型定义的末尾不要忘了
;。
例如:
cpp
struct Student {
string name;
int age;
float height, weight;
char hobby[2][20];
};2 定义结构体变量
假设我们有了上面的结构体类型 Student,那么我们可以这样定义结构体变量(就像使用其他基本类型一样):
cpp
// 定义结构体变量
Student temp;
// 定义结构体变量的同时进行初始化
Student stu = {"xiaoming", 16, 178.1, 60.09, "篮球", "足球"};
// 定义结构体变量数组
Student stus[100];当然了,对于竞赛生来说更常用的写法是这样的(在声明结构体类型的同时定义需要用到的结构体变量):
cpp
struct Student {
string name;
int age;
float height, weight;
char hobby[2][20];
} stus[100];3 使用结构体变量
3.1 整体性
结构体变量是不同数据类型的集合,是一个整体,因此它是可以进行整体操作的。
例如:
cpp
stus[1] = stus[2];
swap(stus[0], stus[1]);3.2 访问成员
如果想访问结构体的成员变量,可以使用成员运算符(.)。
例如:
cpp
cout << stu.name << endl;;
printf("%d %.2f %.2f %s\n", stu.age, stu.height, stu.weight, stu.hobby[0]);4 习题
4.1 YBT 1178:成绩排序
cpp
#include <bits/stdc++.h>
using namespace std;
struct Stu {
string name;
int score;
} stu[25];
int n;
bool cmp(const Stu& a, const Stu& b) {
if (a.score == b.score) return a.name < b.name;
return a.score > b.score;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> stu[i].name >> stu[i].score;
}
sort(stu, stu + n, cmp);
for (int i = 0; i < n; i++) {
cout << stu[i].name << " " << stu[i].score << endl;
}
return 0;
}sort 是 algorithm 头文件中的一个排序函数。
使用方式:
对区间 a[begin, end) 进行排序
sort(begin, end, cmp);
1. begin:区间起始地址
2. end:区间末尾元素地址的下一个地址
3. cmp:自定义比较函数,某些情况下可省略,默认升序排序例如:
cpp
int a[100];
// 升序排序
sort(a, a + 100);
// 降序排序
bool cmp(int a, int b) {
return a > b;
}
sort(a, a + 100, cmp);自定义比较函数的注意事项:
- 函数名不必是
cmp,推荐使用cmp。 - 返回值类型必是
bool。 - 参数
a, b的类型和待排序区间的数据类型必定一致。 return返回的是a, b的大小关系。
4.2 YBT 1179:奖学金
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 310;
struct Stu {
int id, a, b, c;
} stu[N];
int n;
bool cmp(const Stu &a, const Stu &b) {
return a.a + a.b + a.c > b.a + b.b + b.c ||
(a.a + a.b + a.c == b.a + b.b + b.c && a.a > b.a) ||
(a.a + a.b + a.c == b.a + b.b + b.c && a.a == b.a && a.id < b.id);
}
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
stu[i].id = i + 1;
cin >> stu[i].a >> stu[i].b >> stu[i].c;
}
sort(stu, stu + n, cmp);
for (int i = 0; i < 5; i++) {
cout << stu[i].id << " " << stu[i].a + stu[i].b + stu[i].c << endl;
}
return 0;
}4.3 YBT 1183:病人排队
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
struct Person
{
string id;
int num, age;
} p[N];
int n;
bool cmp(const Person &a, const Person &b)
{
if (a.age >= 60 && b.age >= 60)
{
if (a.age > b.age)
return true;
else if (a.age < b.age)
return false;
else
return a.num < b.num;
}
else if (a.age < 60 && b.age < 60)
{
return a.num < b.num;
}
else
{
if (a.age >= 60)
return true;
else
return false;
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; ++i)
{
p[i].num = i + 1;
cin >> p[i].id >> p[i].age;
}
sort(p, p + n, cmp);
for (int i = 0; i < n; ++i)
{
cout << p[i].id << endl;
}
return 0;
}