【问题标题】:qsort and std::sort behaving differentlyqsort 和 std::sort 表现不同
【发布时间】:2016-11-27 07:59:29
【问题描述】:

我很惊讶通过qsortstd::sort 进行排序可以产生不同的结果。我需要帮助解释以下 sn-ps 的行为:

  1. 使用qsort:

    // the following comparator has been used in qsort.
    // if l<r : -1, l==r : 0 , l>r 1
    int cmpre(const void *l, const void *r) {
        if ((*(tpl *)l).fhf < (*(tpl *)r).fhf)
            return -1;
        else
        if ((*(tpl *)l).fhf == (*(tpl *)r).fhf) {
            if ((*(tpl *)l).nhf == (*(tpl *)r).nhf)
                return 0;
            else
            if ((*(tpl *)l).nhf > (*(tpl *)r).nhf)
                return 1;
            else
                return -1;
        } else
            return 1;
    }
    
    // and sort statement looks like : 
    qsort(tlst, len, sizeof(tpl), cmpre);
    

    完整代码链接 => http://ideone.com/zN87tX

  2. 使用排序:

    // the following comparator was used for sort 
    int cmpr(const tpl &l, const tpl &r) {
        if (l.fhf < r.fhf)
            return -1;
        else
        if (l.fhf == r.fhf) {
            if (l.nhf == r.nhf)
                return 0;
            else
            if (l.nhf > r.nhf)
                return 1;
            else
                return -1;
         } else
             return 1;
    }
    // and sort statement looks like : 
    sort(tlst, tlst + len, cmpr);
    

    完整的代码链接在 => http://ideone.com/37Dc2S

您可以在链接上看到排序操作前后的输出,并可能希望查看用于比较两个元组的comprcompre 方法。我不明白为什么sort 不能对数组进行排序,而qsort 可以这样做。

【问题讨论】:

  • qsortsort的比较函数规范不同

标签: c++ sorting qsort


【解决方案1】:

cmpr()重写为

bool cmpr(const tpl &l, const tpl &r){
    if(l.fhf != r.fhf) return l.fhf < r.fhf;
    return l.nhf < r.nhf;
}

或者,您也可以重用cmpre() 来实现cmpr()

bool cmpr(const tpl &l, const tpl &r) {
    return (cmpre(&l, &r) < 0);
}

【讨论】:

  • 为什么 sort 和 qsort 的比较函数不同。感谢您及时回复 。 :-) 我的意思是为什么 C++ 期望 sort 和 qsort 的比较函数具有不同的性质。他们这样做的设计师可能会想到什么。
  • @prem qsort 来自 C。它们是由不同的人编写并为不同的人编写的非常不同的代码库。在 C++ 中,sort 需要类似于 &lt; 的内容,后者返回 bool。在 C 中,没有这样的约束。
猜你喜欢
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 2012-03-09
  • 2010-09-20
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多