一种排序问题 南洋理工学院
学习要点
- 用sort函数对struct类型进行排序,sort(rec, rec + m, cmp)
其中,cmp函数表示比较方法,注意,当两个内容完全相同时,应该返回false,否则会报错- 使用sort函数和puts(“”)时,需包含头文件algorithm 和 stdio
描述
现在有很多长方形,每一个长方形都有一个编号,这个编号可以重复;还知道这个长方形的宽和长,编号、长、宽都是整数;现在要求按照一下方式排序(默认排序规则都是从小到大);
1.按照编号从小到大排序
2.对于编号相等的长方形,按照长方形的长排序;
3.如果编号和长都相同,按照长方形的宽排序;
4.如果编号、长、宽都相同,就只保留一个长方形用于排序,删除多余的长方形;最后排好序按照指定格式显示所有的长方形;
输入
第一行有一个整数 n为(0, 10000),表示接下来有n组测试数据;
每一组第一行有一个整数 m为(0, 1000),表示有m个长方形;
接下来的m行,每一行有三个数 : 第一个数表示长方形的编号,第二个和第三个数值大的表示长,数值小的表示宽,相等说明这是一个正方形(数据约定长宽与编号都小于10000);
输出
顺序输出每组数据的所有符合条件的长方形的 编号 长 宽
样例输入
1
8
1 1 1
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
样例输出
1 1 1
1 2 1
1 2 2
2 1 1
2 2 1
参考代码如下:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
// struct for rectangle
struct recTangle
{
int num;
int length;
int width;
};
// when every parameter is the same, must return false
bool cmp(recTangle a, recTangle b)
{
if(a.num < b.num)
return true;
else if((a.num == b.num) && (a.length < b.length))
return true;
else if ((a.num == b.num) && (a.length == b.length) && (a.width < b.width))
return true;
else
return false;
}
int main()
{
int a = 0, iRecTest = 0;
recTangle rec[2000];
cin >> a; // num of test
// get value of each recTangle
for (int i = 0; i < a; i ++)
{
cin >> iRecTest; // num of rectangle
for (int j = 0; j < iRecTest; j++) // for each test
{
cin >> rec[j].num >> rec[j].length >> rec[j].width;
if (rec[j].length < rec[j].width)
{
int temp;
temp = rec[j].length; rec[j].length = rec[j].width; rec[j].width = temp;
}
}
sort(rec, rec+iRecTest, cmp);
// print value of recTangle
printf("%d %d %d", rec[0].num, rec[0].length, rec[0].width);
puts("");
for (int i =1; i<iRecTest; i++)
{
if(!((rec[i].num == rec[i-1].num) && (rec[i].length == rec[i-1].length) && (rec[i].width == rec[i-1].width)))
{
printf("%d %d %d", rec[i].num, rec[i].length, rec[i].width);
puts("");
}
}
}
system("pause");
return 0;
}