简体   繁体   English

将比较函数写入 qsort 以按指定字段对结构数组进行排序?

[英]Write compare function to qsort to order array of structs by specified field?

I have the following struct:我有以下结构:

struct Variant{
    char name[50];
    int age;
    long long int temporal_aura;
    char timeline[50];
    char status;
};

I'll have an array of structs and I want to sort it by any of the fields above (name, age, temporal_aura, timeline, status).我将有一个结构数组,我想按上述任何字段(名称、年龄、temporal_aura、时间线、状态)对其进行排序。 The field used to sort the array will be given by the user.用于对数组进行排序的字段将由用户提供。 For example:例如:

void sort_struct(Variant **variants, int n, char *field){
    if(!strcmp(field,"name"))
        qsort(variants, n, sizeof(Variant), compare);

    if(!strcmp(field,"age"))
        qsort(variants, n, sizeof(Variant), compare);

    if(!strcmp(field,"temporal_aura"))
        qsort(variants, n, sizeof(Variant), compare);

    if(!strcmp(field,"timeline"))
        qsort(variants, n, sizeof(Variant), compare);

    if(!strcmp(field,"status"))
        qsort(variants, n, sizeof(Variant), compare);
}

My problem is: will I have to write a compare function to each member of the struct?我的问题是:我是否必须为结构的每个成员编写一个比较函数? Is there any way to optimize a compare function to this code?有什么方法可以优化此代码的比较函数吗?

will I have to write a compare function to each member of the struct?我是否必须为结构的每个成员编写一个比较函数?

Yes.是的。
(Unless you want a dirty "pass info in a global variable" solution). (除非您想要一个肮脏的“在全局变量中传递信息”解决方案)。

Research qsort_r() for a qsort() alternative.研究qsort_r()以获得qsort()替代方案。


BTW, I would have expected qsort(variants, n, sizeof(Variant*), compare);顺便说一句,我本来希望qsort(variants, n, sizeof(Variant*), compare); (note: the * ) or better as qsort(variants, n, sizeof *variants, compare); (注意: * )或更好的qsort(variants, n, sizeof *variants, compare);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM