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;
}
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.
Thanks.
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);
Then after you try that, go back and use std::sort
instead. 8v)