极光 · STL库测试 · Sort与Struct

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数组)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

影月丶暮风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值