使用qsort()和类指针 [英] Using qsort() with class pointers
问题描述
我使用内置函数 qsort()
来排序类项目
指针的向量。
I am using the in-built function qsort()
to sort a vector of class item
pointers.
class item {
int value;
vector<char> c;
...
...
};
//Declaration of vector
vector<item*> items;
//Function Call
qsort(&items, items.size(), sizeof(item*), value_sort);
int value_sort(const void* a, const void* b)
{
item* pa = *(item**) a;
item* pb = *(item**) b;
if (pb->value < pa->value)
return 1;
else if (pa->value < pb->value)
return -1;
return 0;
}
在调试器模式下,指针既不是 pa
或
pb
指向有效的位置。由 pa
或 pb $指向的
类项目
的所有数据成员的集合c $ c>包含垃圾值。我在哪里犯错误?我也不确定使用双指针。
In the debugger mode, pointers neither pa
nor pb
point to a valid location. Set of all data members of the class items
pointed by either pa
or pb
contain garbage values. Where am I making a mistake? I am also not certain on the usage of double pointers.
谢谢。
推荐答案
我同意使用 std :: sort
建议的答案。但是忽略这一点,我认为你的问题的原因是你传递向量
对象的地址,而不是向量的内容。尝试这样:
I agree with the answers that advise using std::sort
. But ignoring that for the moment, I think the reason for your problem is that you're passing the address of the vector
object, not the contents of the vector. Try this:
//Function Call
qsort(&items[0], items.size(), sizeof(item*), value_sort);
然后在您尝试之后,返回并使用 std :: sort
。 8v)
Then after you try that, go back and use std::sort
instead. 8v)
这篇关于使用qsort()和类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!