如何在c中使用qsort比较C ++字符串? [英] How to compare C++ string using qsort in c?

查看:150
本文介绍了如何在c中使用qsort比较C ++字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习c库的qsort函数 stdlib 。这在 c ++ 中也提供。但我不明白如何使用它们排序 c ++ 字符串。我不知道参数应该为 sizeof()运算符和是否 compare_str 代码是正确的。我试过这个代码:

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 c++ strings. I am not sure of what the parameters should be for the sizeof() operator and whether my compare_str code is right. I tried this code:

    #include<iostream>
    #include<cstdlib>
    using namespace std;
    #include<string>

    int compare_str( const void *a, const void *b){
       string  obj = (const char*)a;
       string obj1 = (const char*)b;
       return obj.compare(obj1);
    }
    int main(){
        string obj[4] = {"fine", "ppoq", "tri", "get"};
        qsort(obj, 4, sizeof(obj[0].length()), compare_str);
        for( int i=0; i<4; i++)
            cout<<obj[i]<<endl;
        return 0;
    }

我的输出是:

ppoq
tri
get
fine

我无法弄清楚错误。请帮助。

I am not able to make out the error. Please help.

推荐答案

您不能,也不能在使用 qsort 数组 std :: string s。元素必须是琐碎类型,哪些字符串不是,因此行为是未定义的。从25.5 / 4(qsort):

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.

原因是 qsort code>会将 memcpy 周围的数组元素,这对于C ++对象一般是不可能的(除非它们足够简单)。

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).

如果你有一个简单的类型,你可以使用这个通用的qsorter比较器(但是这是一个可怕的想法, c $ c> std :: sort 总是优选的):

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 <typename T>
int qsort_comp(void const * pa, void const * pb)
{
    static_assert<std::is_trivial<T>::value, "Can only use qsort with trivial type!");

    T const & a = *static_cast<T const *>(pa);
    T const & b = *static_cast<T const *>(pb);

    if (a < b)  { return -1; }
    if (b < a)  { return +1; }
    return 0;
}

使用: T arr [N]。 qsort(arr,N,sizeof * arr,qsort_comp" T);


不要使用这个。改用 std :: sort

这篇关于如何在c中使用qsort比较C ++字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆