如果我在C中有一个坐标为x和y的结构POINT,那么通过该对的第一个元素对它进行排序的可接受方式是什么,然后如果第一个相等则是第二个?我在C++中找到了很多答案,但在C..中却没有.你可以帮忙吗?
只需使用qsort和适当的比较函数,例如
// point type
typedef struct {
int x;
int y;
} Point;
// point compare function
int compare_points(const void *p1, const void *p2)
{
const Point *pt1 = p1;
const Point *pt2 = p2;
// do primary compare on x
if (pt1->x > pt2->x)
return 1;
if (pt1->x < pt2->x)
return -1;
// pt1->x == pt2->x - do secondary compare on y...
if (pt1->y > pt2->y)
return 1;
if (pt1->y < pt2->y)
return -1;
// pt1 == pt2
return 0;
}
// sort an array of points...
qsort(points, num_points, sizeof(Point), compare_points);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |