简体   繁体   中英

Qsort doesn't sort properly array of strings

I'm trying to sort array declared as string *names1 = new string[1]; (the size of an array is growing with adding more items).

I'm putting there strings. The items in array before sorting are: novot svobodovaa novakj6 3 vondraj1234

after calling qsort(names1, size, sizeof (string), compare); , where compare is implemented like this

int compare(const void * a, const void * b) {
return ( *(char*) a - *(char*) b);
}

the items in my array are scrambled this way vondraj1234 novakj6 novot svobodovaa

Does anybody know, where can be the bug that doesn't allow me to sort the array in alphabetical order?

You can only use qsort with types that can be copied with memcpy . std::string (and any other type with a non-trivial assignment operator) does not qualify. Instead, use std::sort . It knows how to copy objects correctly.

I'm going to nitpick at the somewhat poor quality of your question first, bear with me.

string *names1 = new string[1];

This gives you an array of one (1) string object.

(the size of an array is growing with adding more items)

False. The size of your array might do so, because you hopefully wrote code to this specific end. The size of an array does not automatically adjust. (That is what vector is for.)

I'm putting there strings. The items in array before sorting are: novot svobodovaa novakj6 3 vondraj1234

In one string? Or as an array of strings? In the latter case, I'd like to see some proof, like thus:

for ( size_t i = 0; i < size; ++i )
{
    std::cout << i << ": " << names1[i] << "\n";
}

Ideally just before your line:

qsort(names1, size, sizeof (string), compare);

(I just hope and assume that size actually is the correct size of names1 , another thing that my little loop above would prove.)


The real reason for your troubles is, however, this line:

return ( *(char*) a - *(char*) b);

You're casting string * (pointer to object) to char * (pointer to plain old data), and you are doing it C style ( char* ) instead of C++ style ( static_cast< char * >() ), so your compiler cannot even complain properly.

When you are dereferencing those two pointers, you get the first byte of the two string objects, respectively. This is most likely not the first character of the contained string, but either a jump table or machine code. Hence the somewhat random result...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM