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

前端 未结 6 557
时光说笑
时光说笑 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:28

    You should use the std::sort template function provided by the C++ standard library (in the header file). By default, std::sort uses the less than comparison operator to order elements (std::string already implements operator<). If you need to specify an ordering condition (for example, case insensitive string compare), std::sort allows you to specify an ordering function object.

    Example:

    #include 
    #include 
    
    bool caseInsensitiveOrdering(const std::string& lhs, const std::string& rhs)
    {
       // return true if lowercase lhs is less than lowercase rhs
    }
    
    int main()
    {
        std::string names[] = {"chuck", "amy", "bob", "donna"};
        size_t nameCount = sizeof(names) / sizeof(names[0]);
    
        // Sort using built-in operator<
        std::sort(names, names + nameCount);
    
        // Sort using comparison function
        std::sort(names, names + nameCount, &caseInsensitiveOrdering);
    }
    

提交回复
热议问题