繁体   English   中英

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

[英]C++ qsort inside function on array of structs

再次,我正在处理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) 您有一个zipType*数组, zipType*不是int

但是,由于您使用的是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM