ajmartin
ajmartin

Reputation: 2409

Using qsort() with class pointers

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.

Upvotes: 4

Views: 7681

Answers (3)

UmmaGumma
UmmaGumma

Reputation: 5693

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);

Upvotes: 3

Fred Larson
Fred Larson

Reputation: 62113

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)

Upvotes: 6

Mark B
Mark B

Reputation: 96301

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);

Upvotes: 4

Related Questions