在结构数组上C++ qsort 内部函数

C++ qsort inside function on array of structs

本文关键字:qsort 内部函数 C++ 结构 数组      更新时间:2023-10-16

>我再次,我正在研究zipType数组的qsort。我写的比较函数看起来像这样:

    int compare(const void *v1, const void *v2){
        const struct zipType *p1 = v1;
        const struct zipType *p2 = v2;
        if (p1->postalCode > p2->postalCode)
            return(+1);
        else if (p1->postalCode < p2->postalCode)
            return(-1);
        else
            return(0);
        }

这是使用它的函数:

   void binRead(zipType *zip, fstream *input){
   int junk;
   int count;
   int end;
   input->seekg(0,ios::end);
   end=input->tellg();
   count=input->tellg()/24;
   input->seekg(0);
   while(input->tellg()!=end){  
    for(int i=0;i<count;i++){
        input->read((char*)( &(zip[i].postalCode) ), sizeof(int    ));
        input->read((char*)( &junk ),                sizeof(int    ));
        input->read((char*)( &(zip[i].longitude)  ), sizeof(double  ));
        input->read((char*)( &(zip[i].latitude)   ), sizeof(double  ));
        cout << "Currently at position" << input->tellg() << endl;
     }
   }
   cout << "Array Created, Please wait while I sort" << endl;
   qsort(zip, count, sizeof(int), compare);
   usleep(3000000);
   cout << "Array Sorted" << endl;
  }

我得到的错误是其中几个:

    invalid conversion from ‘const void*’ to ‘const zipType*’ [-fpermissive]
    const struct zipType *p2 = v2;

其中之一:

     error: cannot convert ‘zipType’ to ‘void*’ for argument ‘1’ to ‘void qsort(void*, size_t, size_t, int (*)(const void*, const void*))’
     qsort(*zip, count, sizeof(int), compare);

知道我应该做什么吗?

要修复第一个错误,您需要从比较例程中的void*强制转换:

auto p1 = static_cast<const struct zipType*>(v1);

为了修复第二个错误,我认为我们再次需要投射,但这次要void*

qsort(static_cast<void*>(zip), count, sizeof(zipType*), compare)

老实说,我不确定为什么需要这个演员阵容。如果我正确记住了转换规则,zipType*应该可以隐式转换为void*。如果有人知道,请发表评论,我会编辑答案,或者,如果可以的话,只编辑答案。

请注意,您希望数组中元素的大小用于第三个参数,而不是此处sizeof(int)。您有一组不int zipType*

由于您使用的是C++(推断是因为您使用的是std::cout),但是请尝试std::sort。它更安全,通常可以更好地优化。

std::sort(zip, std::advance(zip, count), compare)

另外,由于这是C++,因此您无需说struct zipType。你可以说zipType.

你应该先读 qsort。然后您将知道每个参数的含义。

你的 qsort 应该是这样的: qsort((void*)zip, count, sizeof(struct zipType), compare);

第三个参数size表示数组中 elem 的大小,应zipType而不是int