How to compare C++ string using qsort in c?

前端 未结 6 558
时光说笑
时光说笑 2020-12-21 08:49

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

6条回答
  •  猫巷女王i
    2020-12-21 09:25

    Better be C++ oriented and use std::sort for your array:

    #include 
    #include 
    #include 
    #include 
    
    int main() {
    
       std::string obj[4] = {"fine", "ppoq", "tri", "get"};
       std::sort(obj, obj + 4);
       std::copy(obj, obj + 4, std::ostream_iterator(std::cout, "\n"));
    }
    

    AFAIK - std::sort uses quick sort.

    [UPDATE] See comments, std::sort is not always pure quick sort.

    [UPDATE2]

    If you want to learn qsort - change std::string to const char* and define function based on strcmp. Remember that qsort passes pointers to elements in an array - so dereference const void* to get const char*. See:

    #include 
    #include 
    
    int compare_cstr(const void* c1, const void* c2) 
    { 
       return strcmp(*(const char**)(c1), *(const char**)(c2)); 
    }
    
    int main() {
    
       const char* obj[4] = {"fine", "ppoq", "tri", "get"};
       qsort(obj, 4, sizeof(obj[0]), compare_cstr);
       std::copy(obj, obj + 4, std::ostream_iterator(std::cout, "\n"));
    }
    

提交回复
热议问题