在c++中排序时输出错误
getting wrong output while sorting in C++
下面的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的来源)
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 使用复制构造函数的程序输出错误
- 异或字符串加密/解密输出错误
- 在linux上使用g++输出错误,在windows上更正
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- ECDSA 密钥对生成输出错误
- fscanf() 输出错误的值
- 输入 1024 后十进制到二进制转换的输出错误?
- 输出错误命令的条件语句
- cuSparse (cusparseDcsrgemm) 中的矩阵乘法输出错误的结果
- 为什么 du -sh 输出错误大小的内存映射文件
- VS2017 的输出错误,但 mingw 有效
- 如何使FFMPEG C 代码不输出错误消息
- 乘以时输出错误.这是我编译器中的错误吗?C
- 输出错误:两个不同编译器上的不同输出:Prime Cryptarithm USACO
- 为什么输出错误崩溃
- C++输入/输出错误
- 尝试用 c++ 制作一个简单的加法器.编译成功,但输出错误
- 当我使用此合并排序代码运行时,输出错误
- 递归功能输出错误的值