0

再说一次,我正在研究zipType's 数组的 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);

任何想法我应该做什么?

4

2 回答 2

1

要修复第一个错误,您需要从void*比较例程内部进行转换:

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

要修复第二个错误,我认为我们需要再次转换,但这次是void*

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

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

请注意,您需要第三个参数的数组中元素的大小,而不是sizeof(int)此处。你有一个zipType*not数组int

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

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

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

于 2013-11-15T05:02:14.813 回答
0

你应该先阅读qsort 。然后你就会知道每个参数的含义。

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

第三个参数size表示数组中元素的大小,应该zipType不是int

于 2013-11-15T04:56:09.290 回答