如何根据其中一个成员的值对结构数组进行排序,从而在另一个成员的基础上断开联系
How to sort an array of structures according to values of one of its members, breaking ties on the basis of another member?
>假设有一个结构:
struct x
{
int a,b,c;
};
结构数组包含 arr[0]={4,2,5}, arr[1]={6,3,1}, arr[2]={4,1,8}
那么我们如何根据成员"a"的值按升序对这个数组进行排序。平局将根据成员"B"的值被打破。
所以排序后的数组应该是:arr[2],然后是arr[0],然后是arr[1]。
我使用了qsort(arr,n,sizeof(struct x),compare);
比较函数定义为
int compare(const void* a, const void * b)
{
return (*(int*)a-*(int*)b);
}
如果我必须打破与成员 b 的关系,我该怎么做修改(目前它是在先到先得的基础上中断关系)。
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));
}
将std::sort
与适当的比较器一起使用。此示例使用 std::tie
来实现词典比较,先使用 a
然后使用 b
,但您可以手写自己的字典。唯一的要求是它满足严格的弱排序:
bool cmp(const x& lhs, const x& rhs)
{
return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
}
std::sort(std::begin(arr), std::end(arr), cmp);
或使用 lambda:
std::sort(std::begin(arr),
std::end(arr),
[](const x& lhs, const x& rhs)
{
return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
});
如果您使用的是 C 而不是 C++,则可以通过以下方式完成compare()
:
int compare(const void* a, const void* b) {
struct x s_a = *((struct x*)a);
struct x s_b = *((struct x*)b);
if(s_a.a == s_b.a)
return s_a.b < s_b.b ? -1 : 1; //the order of equivalent elements is undefined in qsort() of stdlib, so it doesn't matter to return 1 directly.
return s_a.a < s_b.a ? -1 : 1;
}
如果要在成员 a 和 b 都相等时根据成员 c 断开关系,请在 compare()
中添加更多 if-else
语句。
相关文章:
- 类成员重新排序
- 如何在 c++11 中静态断言 std::array 类成员进行排序?
- 按类成员的顺序对包含类对象的C++向量进行排序
- 只对向量中的一个类成员进行排序,其他成员保持不变
- 合并 2 个排序的链表。必需的成员函数 bool Merge(List342 &list1):
- 对结构int成员进行排序
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 如何对类成员向量进行排序
- 如何对同一数组索引下的结构成员进行排序?
- 对多个数据成员进行排序
- 根据类成员对同一密钥的多映射元素进行排序
- 在对结构数组的一个成员进行排序后,移动其成员的其余部分
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- 排序链表-移动节点还是交换数据成员
- 如何为涉及对象成员、间接寻址和强制转换的排序算法实现lambda函数
- 使用 #include 按<algorithm>字符串数据成员对类对象的向量进行排序
- 通过私人成员对自定义对象进行排序
- 如何根据其中一个成员的值对结构数组进行排序,从而在另一个成员的基础上断开联系
- 根据数据成员对对象数组进行排序或筛选
- C++列表::按成员排序的类