在结构数组上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)
。您有一组不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
。
相关文章:
- C++ SSE 内部函数:将结果存储在变量中
- C++代码停止工作错误使用cout内部函数
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- 使用英特尔内部函数 (AVX) 中的混合说明
- 英特尔汇编与内部函数,AVX
- 使用SSE内部函数复制少量数据时出现问题
- 在为函数编写单元测试时,我应该模拟所做的内部函数调用吗?
- 用于平铺矩阵乘法的 AVX 内部函数
- 是否可以使用类的析构函数内部函数来重置值?
- 我在理解 AVX 随机内部函数如何为 8 位时遇到一些问题
- 无法执行内部函数 strlen
- COUT 内部函数调用的顺序
- GCC(通过 CUDA)内部函数的编译器错误,但我没有使用任何
- C++ ld 链接器 --wrap 选项不适用于内部函数调用
- 通过Visual Studio将小型结构逐值传递到非内部函数的速度很慢
- 使用内部函数递增数组的特定元素
- 在使用英特尔内部函数对 SIMD 代码进行编程时,如何强制使用 vmovapd 而不是 vmovupd?
- 如何最大限度地减少使用标量 SIMD 内部函数的 SIMD 注册表的双重负载开销
- 有符号整数溢出、内部函数和未定义的行为
- 在结构数组上C++ qsort 内部函数