简体   繁体   English

qsort在c中没有排序我的结构数组

[英]qsort in c not sorting my array of structs

I'm having an issue with my comparison function for qsort. 我的qsort比较函数存在问题。 I've got an array, mGames, of type ListEntry. 我有一个ListEntry类型的数组mGames。 ListEntry looks like this: ListEntry看起来像这样:

struct ListEntry
{
    bool mLocal;
    int  mLastTurnTime;
};

That's actually rather oversimplified, there's more data in there but it's not being used in the sorting so I omitted it. 这实际上是过于简单了,那里有更多的数据,但它没有被用于排序,所以我省略了它。 Anyway, I'm trying to make it so that entries that have mLocal set to true are ordered first. 无论如何,我正在尝试使其具有mLocal设置为true的条目首先被排序。 Problem is, I can't get qsort to order my array whatsoever. 问题是,我无法获得qsort来订购我的数组。 Here's the comparison function: 这是比较功能:

int compare(const void* a, const void* b)
{
    ListEntry* e1 = (ListEntry*)a;
    ListEntry* e2 = (ListEntry*)b;
    if (e1->mLocal && e2->mLocal)
        return 0;
    return e1->mLocal ? -1 : 1;
}

and my call to it: 我的呼唤:

qsort(mGames, mNumGames, sizeof(ListEntry), compare);

where mNumGames is the number of games in the array (7 in my current test case), and mGames is defined as: 其中mNumGames是数组中的游戏数量(在我当前的测试用例中为7),mGames定义为:

ListEntry mGames[MAX_GAMES]; // where MAX_GAMES is 50

When I step into the compare method, e1 and e2 contain their data as expected (as in, I'm not accessing garbage memory or didn't dereference things right). 当我进入比较方法时,e1和e2按预期包含它们的数据(例如,我没有访问垃圾内存或者没有正确解除引用)。

The weird thing is, no matter how I change that comparison method, I can't get the order to change at all. 奇怪的是,无论我如何改变比较方法,我根本无法改变命令。 I must be overlooking something really obvious. 我必须忽视一些非常明显的事情。

Your function is not a partial ordering. 您的功能不是部分订购。 This 这个

if (e1.mLocal && e2.mLocal)
    return 0;

should be in fact 应该是事实

if (e1.mLocal == e2.mLocal)

The point is, once you deal with qsort (and other sorting routines as well, you need to ensure the comparison relation is transitive and antisymmetric. That wouldn't be true in your case. 关键是,一旦你处理qsort (和其他排序例程,你需要确保比较关系是传递和反对称的。在你的情况下这不是真的。

BTW, since you effectively sort only in two classes, it might be faster just to move the elements with .mLocal == 1 to the beginning of the array by something like 顺便说一下,因为你只能在两个类中进行有效排序,所以将.mLocal == 1的元素移动到数组的开头可能会更快

ListEntry *first = beginning of the array, *last = end of the array;
while(first < last) {
  if(!first->mLocal && last->mLocal)
    swap(first, last); // swap the two elements
  if(first->mLocal) first++;
  if(!last->mLocal) last --;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM