Sign in to follow this  
Headkaze

qsort to std::sort

Recommended Posts

I had an array of cards that I sorted using the following

[code]int sortCard(const void *x_, const void *y_)
{
Card **x = (Card **)x_;
Card **y = (Card **)y_;

int rc = -((*x)->IsSelected() - (*y)->IsSelected());

if(!rc)
rc = -((*x)->IsAnimating() - (*y)->IsAnimating());

if(!rc)
rc = -((*x)->GetZ() - (*y)->GetZ());

if(!rc)
rc = ((*x)->GetIndex() - (*y)->GetIndex());

return rc;
}

qsort(m_deck, m_deckCount * CARD_COUNT, sizeof(Card *), sortCard);[/code]

But I've changed the array to be a vector and am attempting to perform the same sort.

[code]struct SortCard
{
int operator()(Card* a, Card* b)
{
int rc = -(a->IsSelected() - b->IsSelected());

if(!rc)
rc = -(a->IsAnimating() - b->IsAnimating());

if(!rc)
rc = -(a->GetZ() - b->GetZ());

if(!rc)
rc = (a->GetIndex() - b->GetIndex());

return rc;
}
};

std::sort(m_deck.begin(), m_deck.end(), SortCardId());[/code]

But this is not working (it crashes the DS). How can I get the same sort working?

Share this post


Link to post
Share on other sites
What's the type of m_deck?
Can you debug on the device?
If you can't debug on the device (really???), just comment out the code in the compare function, to see which line cause the problem?

In your qsort version the parameter is pointer to pointer, but in std::sort version it's pointer, is this the problem?

Share this post


Link to post
Share on other sites
You need to adjust your comparison function, because [i]qsort [/i]and [i]std::sort[/i] have different semantics with regards to the return value of the comparison function. For [i]qsort[/i], the return value shall return a negative, zero or a positive value if the left hand side is smaller, equal to, or greater than the right hand side, respectively. For [i]std::sort[/i], the function shall only return a [i]bool[/i], stating whether the left hand side is less than the right hand side or not. These semantics are not directly compatible.

Share this post


Link to post
Share on other sites
Unfortunately I don't have a debugger set up. I believe you can use Insight for the Nintendo DS but I don't have it set up.

This seems to have solved the problem

[code]struct SortCard
{
bool operator()(Card* a, Card* b)
{
int rc = -(a->IsSelected() - b->IsSelected());

if(!rc)
rc = -(a->IsAnimating() - b->IsAnimating());

if(!rc)
rc = -(a->GetZ() - b->GetZ());

if(!rc)
rc = (a->GetIndex() - b->GetIndex());

return (rc < 0);
}
};[/code]

Thanks for the reply

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this