gpt4 book ai didi

c - 如何使用 qsort() 对这个结构进行排序?

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:32 25 4
gpt4 key购买 nike

我有这些结构,

 typedef struct
{
int votos; //Votes
float classifica; //Rating
char* titulo; //Title
int ano; //Year
} vg_elemento;

/**
* this register has a vetorg of elements a counter for the size and a counter for the capacity
*/
typedef struct
{
/** numero de elementos do vetorg */
int tamanho; //size

/** capacidade do vetorg */
int capacidade; //capacity

/** array of stored elements */
vg_elemento* elementos;

} vetorg;

我听说有一个 qsort() 函数可以让我对数组进行排序,我试着上网查了一下,但所有的例子要么使用 int、float 要么使用字符串。如何使用上述结构使用 qsort() 函数?

我有一些比较函数,已经给出了:

 typedef int (*comp)(const vg_elemento a, const vg_elemento b);

int comp_ano_asc(const vg_elemento a, const vg_elemento b){ //sorts bt year
if(b.ano > a.ano)
return -1;
if(a.ano > b.ano)
return 1;
return 0;
}

int comp_votos_asc(const vg_elemento a, const vg_elemento b) //sorts by votes
{
if(b.votos > a.votos)
return -1;
if(a.votos > b.votos)
return 1;
return 0;
}

int comp_classifica_asc(const vg_elemento a, const vg_elemento b) //sorts by rating
{
if(b.classifica > a.classifica)
return -1;
if(a.classifica > b.classifica)
return 1;
return 0;
}

int comp_titulo_asc(const vg_elemento a, const vg_elemento b) //sorts by title (alphabetically)
{
if(strcmp(b.titulo,a.titulo)>0)
return -1;
if(strcmp(a.titulo,b.titulo)>0)
return 1;
return 0;
}

我想使用函数对数组进行排序,在该函数中调用 qsort()。例如:

    int vetorg_ordena(vetorg* vec, comp ordem){

//sorts the array according to ordem in an ascending order. returns 0, if successful
}

这是大小为 3 的示例数组的示例:

Votes Rating Year Title
319656 8.8 2010 Inception
511125 8.8 2008 The Dark Knight
227431 8.3 1983 Star Wars: Episode VI - Return of the Jedi

最佳答案

如果您阅读例如this qsort reference您会看到比较函数已通过指针。它传递的指针是指向正在排序的数组中的元素的指针。

因此,如果您有一个 vg_elemento 数组,例如

vg_elemento videos[SOME_SIZE];

然后比较函数基本上就是调用like

comp(&videos[i], &videos[j]);

这反过来意味着你的函数应该看起来像

int comp_ano_asc(const void *a, const void *b){ //sorts bt year
const vg_elemento *va = (vg_elemento *) a;
const vg_elemento *vb = (vg_elemento *) b;

if(vb->ano > va->ano)
return -1;
if(ba->ano > vb->ano)
return 1;
return 0;
}

关于c - 如何使用 qsort() 对这个结构进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com