sort自定义排序的尝试使用

该博客演示了如何使用C++的sort函数进行自定义排序,当遇到连续日期相同的元素时,对这一组进行内部排序。排序依据是成员变量`sn`,保持整体0-9的升序排列。示例中创建了一个Sales类,包含日期、数值和排序序号字段,并给出了排序前后的数据展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sort(first,last cmp) 自定义排序,这里sort在循环里面应该只执行两次,被设定成出现连续的date的值相等得时候才把这一组进行排序,排序之后的number依然遵从全体排序的0-9

//
// Created by Alan on 2022/4/30.
//

#include<bits/stdc++.h>
using namespace std;
class Sales
{
public:
    string date;  //日期
    int sn;       //数值
    int number;   //排序序号
};

bool cmp(Sales a, Sales b)
{
    return a.sn < b.sn; //从小到大排序(升序)
}

int main()
{
    Sales test[10];
    for(int i=0;i<5;i++){
        test[i].date = "2020.4.30";
        test[i].sn = i+100;
        test[i].number = i;
        test[i+5].date = "2020.5.01";
        test[i+5].sn = i+200;
        test[i+5].number = i+5;
    }
    test[3].sn = 15;
    test[8].sn = 60;

    cout << "原始数据:\n";
    for(int i = 0; i < 10; i++){
        cout << "日期" << test[i].date << "\t数值" << '\t' << test[i].sn << "\t排序序号" << '\t' <<  test[i].number << endl;
    }

    int i = 0;
    while(i < 10){
        int j = i;
        int m = 0;
        if(j+1 < 10){
            while(test[j].date == test[j+1].date){
                m++;
                j++;
            }
            sort(test+i,test+i+m,cmp);
            for (int t = i; t <= i + m; t++){
                test[t].number = t;
            }
            i = j + 1;
        }
    }

    cout << "把连续的date值相等的行看做一组,组内按照cmp函数的定义顺序进行排序,排序结果:\n";
    for(int i = 0; i < 10; i++){
        cout << "日期" << test[i].date << "\t数值" << '\t' << test[i].sn << "\t排序序号" << '\t' << test[i].number << endl;
    }

    system("pause");
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值