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

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

    You cannot and must not use qsort on an array of std::strings. The elements must be of trivial type, which strings are not, and thus the behaviour is undefined. From 25.5/4 ("qsort"):

    The behavior is undefined unless the objects in the array pointed to by base are of trivial type.

    The reason is that qsort will memcpy the array elements around, which is not possible for C++ objects in general (unless they're sufficiently trivial).


    If you do have a trivial type, you can use this generic qsorter-comparator (but of course this is a terrible idea, and the inlined std::sort is always preferable):

    template 
    int qsort_comp(void const * pa, void const * pb)
    {
        static_assert::value, "Can only use qsort with trivial type!");
    
        T const & a = *static_cast(pa);
        T const & b = *static_cast(pb);
    
        if (a < b)  { return -1; }
        if (b < a)  { return +1; }
        return 0;
    }
    

    Use: T arr[N]; qsort(arr, N, sizeof *arr, qsort_comp);


    Don't use this. Use std::sort instead.

提交回复
热议问题