Search code examples
c++qsort

How to use qsort for string in C++


I want to use qsort function to sort the characters in the strings using C++.

#include<iostream>
#include<string>
#include<cstdlib>

using namespace std;

int compare_str(void const *a,void const *b){
    char const *aa=(char const *)a;
    char const *bb=(char const *)b;

    if(*aa==*bb) return 0;
    else if(*aa>*bb) return 1;
    else return -1;
}
int main(){

    string str="cake";
    int len=str.length();

    qsort(str,len,sizeof(str[0]),compare_str);
    cout<<str;
    return 0;
}

But it throws :

20 42 [Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'void*' for argument '1' to 'void qsort(void*, size_t, size_t, int (*)(const void*, const void*))' 

It would be great if anyone could provide an efficient way to do this.


Solution

  • I strongly recommend the modern method of

    #include <algorithm>
    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string s("cake");
    
        std::sort(s.begin(), s.end());
    
        std::cout << s << std::endl; // Prints "acek".
    
        return 0;
    }
    

    Plus, using std::sort over qsort allows the compiler to optimize better, so it's a win-win...