Using qsort() with class pointers

7.6k Views Asked by At

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.

3

There are 3 best solutions below

2
On BEST ANSWER

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)

2
On

Use std::sort from algorithm. It is easy to use, type safe and faster than qsort and haven't problems with pointers :).

#include <algorithm>

inline bool comparisonFuncion( item *  lhs,item  * rhs)
{
    return lhs->value<rhs->value;
}

std::sort(items.begin(),items.end(),comparisonFunction);
1
On

Don't use qsort in C++, use std::sort instead:

int value_sort(item* pa, item* pb)
{
    return pa->value < pb->value;
}

std::sort(items.begin(), items.end(), value_sort);