Need help sorting

B

Brad Hagen

I am trying to sort a vector of pointers to Foo, and my code looks something
like this:

vector<Foo*> *pNewVector

sort(pNewVector->begin(),
pNewVector->end(),
Foo::SortFunction
);

This was working for a while, but in one case it deadlocks in the sort
function (not Foo::SortFunction but somewhere else, in the standard library
code I guess, I don't know). Is it obvious that this won't work in general?
Thanks for any help.
Brad
 
I

Ivan Vecerina

Hi Brad,

....
| sort(pNewVector->begin(),
| pNewVector->end(),
| Foo::SortFunction
| );
|
| This was working for a while, but in one case it deadlocks in the sort
| function (not Foo::SortFunction but somewhere else, in the standard
library
| code I guess, I don't know). Is it obvious that this won't work in
general?

You should post the body of your sorting function, this is probably where
the problem lies. The function must define a strict ordering, equivalent
to an operator < . In particular, you must never have (a<b) and (b<a).

For example, you should be able to assert:
assert( ! Foo::SortFunction(a,b) || ! Foo::SortFunction(b,a) );

Some implementations of std::sort may enter a deadlock when this condition
is not met (that is, the function returns true in both cases).


I hope this helps,
Ivan
 
B

Brad Hagen

Hi Ivan,

Yes that certainly helped immensely. What I had for the sort function was
this (declared as static):

BOOL Foo::SortFunction(Foo*a, Foo *b)
{
return (a->m_iPriority>=b->m_iPriority);
};

And this didn't work, doubtless for the reason you mention. So now I have
just this:
return (a->m_iPriority > b->m_iPriority);

Which appears to work fine (I wanted descending order).

Thanks a million,
Brad
 
S

Stephen Howe

Yes that certainly helped immensely. What I had for the sort function was
this (declared as static):

BOOL Foo::SortFunction(Foo*a, Foo *b)
{
return (a->m_iPriority>=b->m_iPriority);
};

It won't work when you have multiple m_iPriority that are the same value.
Your SortFunction will return true whichever way a, b are passed as
arguments - exactly what Ivan warned you about.
return (a->m_iPriority > b->m_iPriority);

Which is better. It return false for the same values which is what "less
than" should do.

Stephen Howe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,362
Latest member
ChandaWagn

Latest Threads

Top