如何根据其中一个成员的值对结构数组进行排序,从而在另一个成员的基础上断开联系

How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?

本文关键字:成员 排序 断开 联系 基础上 另一个 数组 何根 一个 结构      更新时间:2023-10-16

>假设有一个结构:

struct x
{
int a,b,c;
};

结构数组包含 arr[0]={4,2,5}, arr[1]={6,3,1}, arr[2]={4,1,8}

那么我们如何根据成员"a"的值按升序对这个数组进行排序。平局将根据成员"B"的值被打破。

所以排序后的数组应该是:arr[2],然后是arr[

0],然后是arr[1]。

我使用了qsort(arr,n,sizeof(struct x),compare);

比较函数定义为

int compare(const void* a, const void * b)
{
return (*(int*)a-*(int*)b);

}

如果我必须打破与成员 b 的关系,我该怎么做修改(目前它是在先到先得的基础上中断关系)。

int compare(const void* a, const void * b){
    struct x x = *(struct x*)a;
    struct x y = *(struct x*)b;
    return x.a < y.a ? -1 : (x.a > y.a ? 1 : (x.b < y.b ? -1 : x.b > y.b));
}

std::sort与适当的比较器一起使用。此示例使用 std::tie 来实现词典比较,先使用 a 然后使用 b ,但您可以手写自己的字典。唯一的要求是它满足严格的弱排序

bool cmp(const x& lhs, const x& rhs)
{
  return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
}
std::sort(std::begin(arr), std::end(arr), cmp);

或使用 lambda:

std::sort(std::begin(arr), 
          std::end(arr),
          [](const x& lhs, const x& rhs)
          {
            return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
          });

如果您使用的是 C 而不是 C++,则可以通过以下方式完成compare()

int compare(const void* a, const void* b) {
    struct x s_a = *((struct x*)a);
    struct x s_b = *((struct x*)b);
    if(s_a.a == s_b.a)
        return s_a.b < s_b.b ? -1 : 1; //the order of equivalent elements is undefined in qsort() of stdlib, so it doesn't matter to return 1 directly.
    return s_a.a < s_b.a ? -1 : 1;
}

如果要在成员 a 和 b 都相等时根据成员 c 断开关系,请在 compare() 中添加更多 if-else 语句。