在c++中排序时输出错误

getting wrong output while sorting in C++

本文关键字:输出 错误 排序 c++      更新时间:2023-10-16

下面的c++代码使用qsort按降序对数组进行排序:

#include<iostream>
#include<cstdio>
#include <stdlib.h>
using namespace std;
struct player {
  double data;
  int index;
};
struct player A[] = {{0.690277,0}, {0.517857,1}, {0.780762,2}, {0.0416667,3}, {0.0416667,4}};
int compare (const void * a, const void * b)
{
   return ( ((struct player*)b)->data - ((struct player*)a)->data );
}
int main ()
{
  int n;
  qsort (A, 5, sizeof(struct player), compare);
  for (n=0; n<5; n++)
  printf ("data=%lf, index=%dn", A[n].data, A[n].index);
  return 0;
}

但是我得到的输出是这样的:

data=0.517857, index=1
data=0.780762, index=2
data=0.041667, index=3
data=0.041667, index=4
data=0.690277, index=0

代码有什么问题吗?

compare中,您正在减去两个sub-1双精度并将它们转换为int,结果在大多数情况下为0。你应该比较它们并返回-1/1,而不是相减。

考虑使用这个比较:

int compare (const void * a, const void * b)
{
    auto x = reinterpret_cast<const player*>(a);
    auto y = reinterpret_cast<const player*>(b);
    if(x->data < y->data)
        return -1;
    if(x->data > y->data)
        return 1;
    return 0;
}

也就是说,这种编码风格已经过时了。

考虑这样写:

#include<iostream>
#include <algorithm>
struct player {
  double data;
  int index;
    bool operator < (const player& p) const
    {
        return data < p.data;
    }
};
auto A = std::vector<player>{
    {0.690277,0}, {0.517857,1},
    {0.780762,2}, {0.0416667,3}, {0.0416667,4}
};
int main ()
{
    std::sort(std::begin(A), std::end(A));
    for(const auto& x: A)
        std::cout << "data=" << x.data << ", "
            << "index=" << x.index << "n";
}

建议修改:

  • 不全局导入std名称
  • 不要混合cstdio和iostreams(只包含其中一个)
  • 使用std::vector或std::array代替原生数组
  • 定义类接口中的排序顺序(bool操作符<)。(这也应该意味着您定义了其他算术运算符——这是一种良好的实践,可以避免以后的细微错误,但对于这个特定的实现来说,编译和工作并不是必需的)
  • 使用std::sort代替qsort
  • 不要使用原始指针(像这样使用它们是bug的来源)