C - 基于另一个元素对结构元素进行排序
C - Sorting struct element based on another element
>我有一个声明如下的 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});
现在,您的人向量将被颠倒排序。
相关文章:
- 使用不带参数的函数访问结构元素
- 带结构的二维矢量:如何存储元素
- 访问类lintalizer列表中的结构元素
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 设计将引用元素移动到开头的数据结构.C++
- 结构元素名称要 cout?
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 从指向结构数组的指针中提取元素
- 继承层次结构并将元素添加到向量
- 在集合中查找使用结构C++的元素
- C++结构元素(成员变量)的数量
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 在C++中更改结构内部元素的方法?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 如何为结构的数据元素赋值
- 如何使用矢量元素将项目添加到结构中?
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 指向结构的指针向量的元素具有相同的地址
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?