I tried to learn the qsort function of the c-library stdlib. This is provided even in c++. But i dont understand how to use them for sorting c++ strings. I am not sure of what the parameters should be for the sizeof() operator and whether my compare_str code is right. I tried this code:
#include<iostream>
#include<cstdlib>
using namespace std;
#include<string>
int compare_str( const void *a, const void *b){
string obj = (const char*)a;
string obj1 = (const char*)b;
return obj.compare(obj1);
}
int main(){
string obj[4] = {"fine", "ppoq", "tri", "get"};
qsort(obj, 4, sizeof(obj[0].length()), compare_str);
for( int i=0; i<4; i++)
cout<<obj[i]<<endl;
return 0;
}
My output was:
ppoq
tri
get
fine
I am not able to make out the error. Please help.
You cannot and must not use
qsorton an array ofstd::strings. The elements must be of trivial type, which strings are not, and thus the behaviour is undefined. From 25.5/4 (“qsort”):The reason is that
qsortwillmemcpythe array elements around, which is not possible for C++ objects in general (unless they’re sufficiently trivial).If you do have a trivial type, you can use this generic qsorter-comparator (but of course this is a terrible idea, and the inlined
std::sortis always preferable):Use:
T arr[N]; qsort(arr, N, sizeof *arr, qsort_comp<T>);Don’t use this. Use
std::sortinstead.