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