sort自定义排序的尝试使用

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;
}

在这里插入图片描述

posted @ 2022-04-30 17:09  在天边偷看小天使  阅读(9)  评论(0)    收藏  举报  来源