【发布时间】:2016-11-27 07:59:29
【问题描述】:
我很惊讶通过qsort 和std::sort 进行排序可以产生不同的结果。我需要帮助解释以下 sn-ps 的行为:
-
使用
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
-
使用排序:
// 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
您可以在链接上看到排序操作前后的输出,并可能希望查看用于比较两个元组的compr 和compre 方法。我不明白为什么sort 不能对数组进行排序,而qsort 可以这样做。
【问题讨论】:
-
qsort和sort的比较函数规范不同。