Reputation: 4990
I am trying to run qsort from cstdlib. The function
qsort( m_all_animals , numberOfAnimals() , sizeof(Animal*) , compare);
executes successfully but it doesn't sort the m_all_animals. Actually, it does nothing to the array. The underlying data structures are here
Animal** m_all_animals;
//the number of elements, I tested it and it works
int numberOfAnimals(){
int result=0;
for (int i=0;i<m_size*2;++i){
if (m_all_animals[i]==NULL)
break;
++result;
}
return result;
}
int compare (const void* p1, const void* p2){
return ((Animal*) p1)->get_size()-((Animal*) p2)->get_size();
}
I have the following inheritance hierarchy if it helps
Animal<-Bear
Bear<-brown_bear
brown_bear<-white_bear
Bear<-panda_bear
Animal<-snail
Upvotes: 1
Views: 221
Reputation: 153810
Don't use qsort()
in C++! It is slow, not type-safe, and will wreck havoc when used on non-POD types. Use std::sort()
instead.
Upvotes: 4
Reputation: 8839
Your pointers are not correct. You have an array of pointers (Animal *
); it should be an array of Animal
data type and not pointer if you want to use your compare
. Or you will need to modify compare
to work with Animal **
.
Upvotes: 2
Reputation: 98348
Yours is an array of pointers to Animal
, so your compare
function actually takes pointers to pointers to Animal
:
int compare (const void* p1, const void* p2){
return (*(Animal**)p1)->get_size()-(*(Animal**)p2)->get_size();
}
Upvotes: 2