Sort-极简
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define s3(x, l, r) sort(x + l, x + r + 1) //从0启存情况
#define s4(x, l, r) sort(x + l, x + r + 1, greater<int>())
int a[15] = {14, 84, 7, 5, 62, 98, 45, 16, 20, 17, 18, 39, 28, 74, 57}, n = 15;
void show()
{
for (int x = 1; x <= n; x++)
printf("%d ", a[x - 1]);
printf("\n");
}
int main()
{
s3(a, 0, n - 1), show();
s4(a, 0, n - 1), show();
// 2022/03/27 由【武守恒】同学提出,区域变量替换方法,极大简化sort写代码的长度
return 0;
}
Sort与结构体
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
using namespace std;
#define s(x) sort(x, x + n);
const int n = 10;
struct node
{
int h, w, n; //身高体重编号
bool operator<(node &t)
{ //新插入t元素,是否合法?身高低,体重轻,序号小的同学往前排,判断优先顺序以此为准
if (h != t.h)
return h < t.h; //新来的升高更高
if (w != t.w)
return w < t.w; //相同升高就看体重,新来的体重更重不变动
return n < t.n; //身高体重都一样的把序号小的往前排布这里认为每个人序号都不同
}
};
node a[12];
void init()
{
int b[20] = {0, 172, 172, 168, 168, 192, 192, 148, 193, 178, 173}; //身高10人
int c[20] = {0, 90, 85, 72, 74, 96, 97, 52, 87, 72, 80};
for (int x = 1; x <= 10; x++)
a[x - 1].h = b[x], a[x - 1].w = c[x], a[x - 1].n = x - 1;
}
void show()
{
for (int x = 0; x < 10; x++)
printf("编号:%d 身高:%d 体重:%d\n", a[x].n, a[x].h, a[x].w);
}
int main()
{
init();
s(a);
show();
return 0;
}
operator合法插入思想
sort中operator部署在结构体内部,只需要设置一个【外来者】插入于右侧
priority_queue中operator部署在结构体外部,需要设置【本体点】和【外来者】两点
在sort中,结构体内hwn视作【本体点】;return是插入合法
比如return n<t.n 即【外来者n】比【本体n】大,那么插入就是合法
最终sort结果就是,小的往前放,大的在后面(不断插入)
优先队列中与这个情况恰好相反,左侧右侧分别部署为本体点和外来者
sort默认是小头在前, priority_queue默认是大头在前(针对单一int数组)