如何根据其成员之一的值,打破另一名成员的基础上,联系排序结构的数组? [英] How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?
问题描述
假设有一个结构:
结构点¯x
{诠释A,B,C;};
结构的数组包含ARR [0] = {4,2,5},编曲[1] = {6,3,1},编曲[2] = {4,1,8}
那么如何可以根据会员的价值,我们进行排序这个数组按升序'一',。
领带会根据成员'B'的价值被打破。
所以排序后的数组应该是:。ARR [2],然后常用3 [0],则常用3 [1]
我用的qsort(ARR,N的sizeof(结构X),比较);
定义为
比较功能 INT比较(常量无效*一,常量无效* B)
{回报(*为(int *)A - *为(int *)B);}
我甲肝什么修改做,如果我要打破平局acccording成员B。(目前是打破先到先得的关系)。
INT比较(常量无效*一,常量无效* B){
结构X X = *(结构X *)一个;
结构x和y = *(结构X *)B: 返回x.a< y.a? -1:(x.a> y.a 1:(x.b&下; y.b -1:x.b> y.b));
}
Suppose there is a structure:
struct x
{
int a,b,c;
};
The array of structure contains arr[0]={4,2,5}, arr[1]={6,3,1}, arr[2]={4,1,8}
then how can we sort this array in ascending order depending on value of member 'a',. tie will be broken according to value of member 'b'.
So array after sorting should be : arr[2],then arr[0], then arr[1].
I have used qsort(arr,n,sizeof(struct x),compare);
with compare function defined as
int compare(const void* a, const void * b)
{
return (*(int*)a-*(int*)b);
}
What modification I hav to do if I have to break ties acccording to member b.(currently it is breaking ties on first come first serve basis).
int compare(const void* a, const void * b){
struct x x = *(struct x*)a;
struct x y = *(struct x*)b;
return x.a < y.a ? -1 : (x.a > y.a ? 1 : (x.b < y.b ? -1 : x.b > y.b));
}
这篇关于如何根据其成员之一的值,打破另一名成员的基础上,联系排序结构的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!