Please enable java script to visit.
NOTEBOOK
HOMEPHP / MySQLJS / HTMLWXappPythonC++Blender其他
【入门】坐标排序【***】 - NOTEBOOK
【入门】坐标排序【***】
C++
Posted on 2023-08-11
摘要 : 学会使用结构体struct,以使用sort定义排序数组。
❱ 描述:

输入n个不同的坐标,按x轴的值从小到大排序,如果x相同,则按照y排序。

❱ 输入描述:

第1行是一个整数n(n<=10000)。
接下来有n行,每行有2个整数,代表了1个点的坐标。

❱ 输出描述:

输出n行,每行有2个整数,输出排序后的n个坐标。

❱ 用例输入:
4
-1 -1
1 1
-1 1
1 -1



❱ 用例输出:
-1 -1
-1 1
1 -1
1 1


// 定义结构体,包含 x y。
struct XYtype{
int x,y;
};
// 定义数组,结构为 XYtype
XYtype p[10002];

// 定义排序,对XYtype结构的排序
bool cmp(XYtype a,XYtype b){
if(a.x != b.x){
return a.x < b.x; // 由小到大
}else{
return a.y < b.y; // 由小到大
}
}

int n; // 输入数组 数量n
int main(){
cin >> n;
for(int i=1;i<=n;i++){
cin >> p[i].x >> p[i].y; // 赋值
}

sort(p+1,p+1+n,cmp); // 使用自定义排序函数cmp

for(int i=1;i<=n;i++){
cout<<p[i].x<<' '<<p[i].y<<endl; // 输出
}
return 0;
}