C++ sort对两列进行排序
时间: 2023-11-14 15:10:43 浏览: 48
可以使用C语言中的qsort函数对两列进行排序。首先定义一个结构体,包含需要排序的两列数据,然后编写比较函数,根据需要排序的列进行比较,最后调用qsort函数进行排序。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Data {
int col1;
int col2;
};
int compare(const void *a, const void *b) {
struct Data *p = (struct Data*)a;
struct Data *q = (struct Data*)b;
if (p->col1 == q->col1) {
return p->col2 - q->col2;
}
return p->col1 - q->col1;
}
int main() {
int n = 5;
struct Data arr[] = {{2, 3}, {1, 2}, {2, 1}, {3, 2}, {1, 3}};
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf("%d %d\n", arr[i].col1, arr[i].col2);
}
qsort(arr, n, sizeof(struct Data), compare);
printf("After sorting:\n");
for (int i = 0; i < n; i++) {
printf("%d %d\n", arr[i].col1, arr[i].col2);
}
return 0;
}
```
输出结果为:
```
Before sorting:
2 3
1 2
2 1
3 2
1 3
After sorting:
1 2
1 3
2 1
2 3
3 2
```
在比较函数中,如果需要按照多个列进行排序,可以根据需要添加比较条件。比较函数的返回值为负数表示第一个参数小于第二个参数,返回值为正数表示第一个参数大于第二个参数,返回值为0表示两个参数相等。