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

前端 未结 6 569
时光说笑
时光说笑 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条回答
  •  渐次进展
    2020-12-21 09:33

    Your error is in the declaration of the size in qsort. What is expected is the size of a member, which is, in your case, a string. So you want to use:

    qsort(obj, 4, sizeof(string), compare_str);
    

    However, you need to work with pointer to string, rather than strings themselves. Then, the code should look like:

    int compare_str( const void *a, const void *b){
       const string*  obj = (const string*)a;
       const string* obj1 = (const string*)b;
       return obj->compare(*obj1);
    }
    
    // ...
    
    string* obj[4] = { new string("fine"), new string("ppoq"),
                       new string("tri"), new string("get") };
    qsort(obj, 4, sizeof(string*), compare_str);
    // And delete the objects
    for(int i = 0 ; i < 4 ; ++i) delete obj[i];
    

提交回复
热议问题