I am using qsort to sort an array of string in c++. My code is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int CompareString( const void * e1, const void * e2) {
string * s1 = (string * ) e1;
string * s2 = (string * ) e2;
if( *s1 < *s2 ) return -1;
else if( *s1 == *s2 ) return 0;
else if( *s1 > *s2 ) return 1;
}
int main() {
string Array[4] = {"hehe","789","456","123"};
qsort(Array,4,sizeof(string),CompareString);
for( int i = 0;i < 4;++i )
cout << Array[i] << endl;
return 0;
}
But it receive runtime error. I do know that sort in works, but I want to know Why I can not use qsort. Thanks :)
This question is similar to This Question But there are some differences. In that question, people suggested using sort instead, or using qsort on trivial types. However, my question is I have to use qsort instead of sort, so my question is not addressed in that question, And I do not consider my question as duplicates.
As to why I have to use qsort instead of sort, the answer is "this is the requirement of the assignment", the link is:Here. I translate the original question as follows:
Implement MyString class, which inherits std:string, and the code should compile and run correctly with the following code:
MyString SArray[4] = {"big","me","about","take"};
qsort(SArray,4,sizeof(MyString), CompareString);
for( int i = 0;i < 4;++i )
cout << SArray[i] << endl;
MyString should be something like:
class MyString:public string{
...
};
This original question requires MyString to pass other tests, which I have passed already. But I still can not pass qsort, So I adapted it and asked my first-version quesion.
From the answers, I can conclude that qsort do not work with non-POD. Since MyString inherits string, and string is non-POD, so MyString is non-POD, therefore MyString can not pass the tests.
Thank you all for answering my question :)
sizeof(string)looks suspicious to me. It means that the algorithm will assume that objects are POD (no C++). Turnstringintoconst char *that will probably work.std::stringis not guaranteed to work withqsort. Read the answers to this question: stackoverflow.com/questions/6174955/…std::sort.qsortis nasty old C. <g>std::string,std::vectorand other standard C++ components but not one of the standard algorithmis.