c++ - 为什么这会在使用内置 qsort 时出错

标签 c++

我写了一些代码,但出现了错误。代码如下:-

  long long int compare (const void * a, const void * b)
   {
     return ( *(long long int*)a - *(long long int*)b );
   }

 long long int number; 
 long long int *ar =(long long int *)(malloc(sizeof(long long int)*number));
 //Took the values of number and  ar from and then performed the following
 qsort(ar,number,sizeof(long long int),compare);

此代码导致以下错误:-

从 long long int (*)(const void*, const void*)' 到 int (*)(const void*, const void*) 的无效转换初始化 void qsort(void*, size_t) 的参数 4 , size_t, int (*)(const void*, const void*))'

我在这里做错了什么?

最佳答案

qsort 需要一个返回类型为 int 的方法,而不是 long long。

因为直接转换为 int 可能会搞砸你的比较函数,你应该做这样的事情(假设你已经将 a 和 b 转换为 long long):

return a < b ? -1 : (a == b ? 0 : 1);

为了符合要求,即:

The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.

关于c++ - 为什么这会在使用内置 qsort 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237056/

相关文章:

c++ - 是否有 C++ "multiset<int>"的 Python 等效项?

c++ - VS 2010,C++中使用 "open"时文件的默认保存路径

c++ - C++ 类构造中的奇怪错误

c++ - 向 Qt 样式表添加特殊性时丢失样式

c++ - 以最新优先格式显示日志数据

c++ - C 字符串和(整数、 double 、 float )之间的动态分配

C++ bitset 问题

c++ - 如何使用具有相对路径的 fstream 对象?

c++ - 使用 ios::ate 重写数据

c++ - 将默认赋值运算符声明为 constexpr : which compiler is right?