4

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
  • 4
    Why are you using qsort? Commented Feb 7, 2011 at 19:45
  • Are you populating the vector? It would help to see that code. As it is, you appear to be sorting an empty vector. Commented Feb 7, 2011 at 19:45
  • @Fred: Yes I am populating the vector. Commented Feb 7, 2011 at 19:56

3 Answers 3

6

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)

Sign up to request clarification or add additional context in comments.

2 Comments

@ajmartin: Cool. But I hope you are heeding the advice about using std::sort. It is cleaner, easier, and less error-prone. Used with a function object, it's likely faster as well. The compiler can take advantage of inlining, which it can't do with the function pointer approach.
Advice taken, and implemented. Thanks :)
4

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

1 Comment

This looks must neater. Thanks
3

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

2 Comments

lhs and rhs aren't pointers (so you'll have a syntax error), but they will need to be to match the contents of the vector.
@Fred Larson I changed in function . to -> but forgot to change references to pointers. Thanks for pointing :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.