C - 基于另一个元素对结构元素进行排序

C - Sorting struct element based on another element

本文关键字:元素 结构 排序 另一个      更新时间:2023-10-16

>我有一个声明如下的 C 结构(只是一个简单的例子):

typedef struct
{
 float score;
 char* name;
}
person;

所以,在整个程序中,我改变了这个人的分数值(我给了他们一个初始值)。因此,我计划将所有分数放在一个向量中并对其进行排序。然后,我想打印一个所有人的名字列表,从最高分数到最小分数。对最后一部分有什么想法吗?我不知道如何编码。谢谢。

与上面的C++方法类似,C 标准库中有一个名为 qsort 的库函数。它基于比较函数,该函数创建数组成员的排序。

对于您的情况,一个最小的示例可能如下所示:

#include <stdlib.h>
#include <stdio.h>
// Definitiion of a person
typedef struct person
{
    float score;
    char *name;
} person;
// Some small epsilon
#define EPSILON 1.0e-3f
// Comaprision function. Returns <0 for a<b =0 for a=b and >0 for a>b
static int compare_people( const void *a, const void *b )
{
    // Cast to the correct pointer type
    const person *p1 = (const person*) a;
    const person *p2 = (const person*) b;
    // There are different ways of comparing floats to each other. In this case we use |a - b| < epsilon for some small epsilon
    float difference = p2->score - p1->score;
    if( difference <= -EPSILON )
    {
        return -1;
    }
    else if( difference >= +EPSILON )
    {
        return +1;
    }
    return 0;
}
int main()
{
    // Initialize list of people
    size_t num_people = 5;
    person people[num_people];
    people[0].score = 0.3f;
    people[0].name = "Homer";
    people[1].score = 1.4f;
    people[1].name = "Marge";
    people[2].score = 0.02f;
    people[2].name = "Bart";
    people[3].score = 13.2f;
    people[3].name = "Lisa";
    people[4].score = 1.0f;
    people[4].name = "Maggie";
    // Print unsorted
    printf( "Unsorted:n" );
    for( size_t i = 0; i < num_people; ++i )
    {
        printf( "  %s - %2.2fn", people[i].name, people[i].score );
    }
    printf( "n" );
    // Sort
    qsort( people, num_people, sizeof(person), &compare_people );
    // Print sorted
    printf( "Sorted:n" ) ;
    for( size_t i = 0; i < num_people; ++i )
    {
        printf( "  %s - %2.2fn", people[i].name, people[i].score );
    }
    printf( "n" );
    // Done
    return EXIT_SUCCESS;
}

请注意有关比较浮点值的注释。

如果您使用的是 Linux,则可以通过查找相应的手册页来研究 C 标准库的系统调用和函数,例如

曼·

例如,

您将有

vector<person> vec;

现在你想使用STL的排序来排序

你首先必须为运算符"<"创建方法

bool operator<(const person& a, const person& b){
    return a.score<b.score;
}

我希望这对你有帮助,我很抱歉我的语法:)

使用示例

sort(vec.begin(),vec.end(),[](const person& a, const person&b){return b<a});

现在,您的人向量将被颠倒排序。