大纲要求
•【3】结构体的定义及应用
User-defined structs
在实际问题中,一组数据往往有不同的数据类型,比如学生,有姓名、学号、语文成绩、数学成绩等等。C++语言给出了一种构造数据类型—“结构体”,结构体在数据存储方面相当于其他高级语言中的记录,但它悠着面向对象的优势。
struct stu{string name;int id;int chinese, math;};
结构体的构造函数
https://blog.csdn.net/a_forever_dream/article/details/88867801
// struct构造函数,说白了,就是初始化// 下面这段代码,看起来很奇怪,可是一定要很熟悉的啊#include <bits/stdc++.h>using namespace std;struct node{int x, y;node(int _x = 0, int _y = 0): x(_x), y(_y){}};int main(){node(2, 3);return 0;}
结构体的小于符号重载


// 下面这段代码,看起来很奇怪,可是一定要很熟悉的啊#include <bits/stdc++.h>using namespace std;struct node{int x, y;node(int _x = 0, int _y = 0): x(_x), y(_y){}bool operator< (const node& W)const{if (x == W.x) return y < W.y;return x < W.x;}};int main(){node A = node(2, 3);node B = node(3, 4);if (A < B) cout << '<' << '\n';else cout << ">=" << '\n';return 0;}
sort()函数
sort函数的特点是非常好用、易用,比赛中,利用这个特点设置坑,让你跳。比如,不管时间复杂度,或者不会看时间复杂度,上来就是sort,然后就肯定超时。就是用sort,也会导致,对数组和下标的理解不完备,导致没有手搓代码的能力。
// 先看一下sort的自定义// 自定义一个cmp函数#include <bits/stdc++.h>using namespace std;int a[110];bool cmp(int a, int b){return a > b;}int main(){int n;cin >> n;for (int i = 0; i < n; i++) cin >> a[i];sort(a, a + n, cmp);for (int i = 0; i < n; i++) cout << a[i] << ' ';puts("");return 0;}
// 如果只是从大到小,还可以使用greater<int>()#include <bits/stdc++.h>using namespace std;int a[110];int main(){int n;cin >> n;for (int i = 0; i < n; i++) cin >> a[i];sort(a, a + n, greater<int>());for (int i = 0; i < n; i++) cout << a[i] << ' ';puts("");return 0;}
// 除了自定义函数,可以结构体的小于符号重载// 以下两个代码,实战意义很大,务必熟练操作// 下面这段代码,看起来很奇怪,可是一定要很熟悉的啊#include <bits/stdc++.h>using namespace std;const int N = 110;struct node{int x, y;node(int _x = 0, int _y = 0): x(_x), y(_y){}bool operator< (const node& W)const{if (x == W.x) return y < W.y;return x < W.x;}}a[N];int n;int main(){cin >> n;for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;sort(a, a + n);for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';return 0;}
#include <bits/stdc++.h>using namespace std;const int N = 110;struct node{int x, y;node(int _x = 0, int _y = 0): x(_x), y(_y){}}a[N];int n;bool cmp(node a, node b){if (a.x == b.x) return a.y < b.y;return a.x < b.x;}int main(){cin >> n;for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;sort(a, a + n, cmp);for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';return 0;}


