Using qsort () with class pointers

I use the built-in qsort() function to sort the class item pointer vector.

 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 debug mode, neither pa nor pb points to a valid location. The set of all class items , indicated by pa or pb , contains garbage values. Where am I mistaken? I'm also not sure about using double pointers.

Thanks.

+4
source share
3 answers

I agree with the answers that advise using std::sort . But ignoring this at the moment, I think the reason for your problem is that you are passing the address of the vector object, not the contents of the vector. Try the following:

 //Function Call qsort(&items[0], items.size(), sizeof(item*), value_sort); 

Then, after you try this, go back and use std::sort . 8v)

+6
source

Do not 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); 
+4
source

Use std :: sort from algorithm . It is easy to use, safe and faster than qsort, and has no problems with pointers :).

 #include <algorithm> inline bool comparisonFuncion( item * lhs,item * rhs) { return lhs->value<rhs->value; } std::sort(items.begin(),items.end(),comparisonFunction); 
+3
source

Source: https://habr.com/ru/post/1338761/


All Articles