【问题标题】:How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?如何根据其中一个成员的值对结构数组进行排序,在另一个成员的基础上打破联系?
【发布时间】:2014-01-22 22:57:09
【问题描述】:

假设有一个结构:

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 打破平局,我需要做哪些修改。(目前是先到先得的原则)。

【问题讨论】:

  • C++ 还是 C?一个好的答案将取决于其中哪一个。
  • 其中任何一个..最好是c

标签: c++ c arrays sorting structure


【解决方案1】:
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));
}

【讨论】:

    【解决方案2】:

    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);
              });
    

    【讨论】:

      【解决方案3】:

      如果你使用 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 语句。

      【讨论】:

      • 那些elses其实是多余的。
      • @BLUEPIXY 没看懂,哪一行会导致溢出?
      • @BLUEPIXY 我明白了,谢谢。没有遇到这种情况,但它确实溢出了。我会编辑答案。
      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多