c++用sort对坐标排序
时间: 2023-11-11 18:01:52 浏览: 113
假设有一个坐标列表,每个坐标都表示为二元组(x, y),可以使用Python的sort函数对其进行排序。
下面是一个示例代码:
```python
coordinates = [(3, 4), (1, 2), (5, 6), (2, 3), (4, 5)]
# 按照x坐标排序
coordinates.sort(key=lambda coord: coord[0])
print(coordinates)
# 按照y坐标排序
coordinates.sort(key=lambda coord: coord[1])
print(coordinates)
```
运行结果:
```
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
```
在上面的代码中,我们首先使用lambda函数指定按照第一个元素(x坐标)或第二个元素(y坐标)进行排序,然后使用sort函数对坐标列表进行排序。
相关问题
用c++语言sort函数对坐标排序
假设有一个存储坐标的结构体:
```c
struct Point {
int x;
int y;
};
```
可以使用`qsort`函数对坐标进行排序,示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct Point {
int x;
int y;
};
int compare(const void *a, const void *b)
{
struct Point *p1 = (struct Point *)a;
struct Point *p2 = (struct Point *)b;
if (p1->x < p2->x) {
return -1;
} else if (p1->x > p2->x) {
return 1;
} else {
return p1->y - p2->y;
}
}
int main()
{
struct Point arr[] = {{3, 4}, {1, 2}, {2, 3}, {1, 3}};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(struct Point), compare);
for (int i = 0; i < n; i++) {
printf("(%d, %d)\n", arr[i].x, arr[i].y);
}
return 0;
}
```
这里定义了一个比较函数`compare`,根据`x`坐标进行升序排序,如果`x`坐标相等,则根据`y`坐标进行升序排序。`qsort`函数将数组`arr`进行排序,排序后输出每个坐标点的值。
用c++语言sort函数对Point类的坐标排序
假设Point类的定义如下:
```
typedef struct Point {
int x;
int y;
} Point;
```
可以使用sort函数对Point类的坐标进行排序,代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Point {
int x;
int y;
} Point;
int compare(const void *a, const void *b) {
Point *p1 = (Point *)a;
Point *p2 = (Point *)b;
if (p1->x != p2->x) {
return p1->x - p2->x;
} else {
return p1->y - p2->y;
}
}
int main() {
Point points[] = {{1, 2}, {3, 1}, {2, 3}, {1, 3}, {3, 2}};
int n = sizeof(points) / sizeof(points[0]);
qsort(points, n, sizeof(Point), compare);
for (int i = 0; i < n; i++) {
printf("(%d, %d) ", points[i].x, points[i].y);
}
printf("\n");
return 0;
}
```
输出结果为:
```
(1, 2) (1, 3) (2, 3) (3, 1) (3, 2)
```
其中,compare函数用于指定排序的比较方式,先按照x坐标排序,如果x坐标相同,则按照y坐标排序。qsort函数是C标准库中的快速排序函数,用于对数组进行排序。