Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-06-27 08:32:22


Nic Roets wrote:
> Often when I write searching or sorting code in C or C++, I'm
> frustrated that I have to make a new "callback type" compare function.
> E.g. when you want to sort a number of points in 2D space according to
> their distance from a reference point, it's tempting to do something
> like
>
> struct Pt {
> int x, y;
> };
>
> static Pt center; // Global or static variable yuck.
>
> int PtDistToCenterCmp (Pt &a, Pt &b)
> {
> return Dist (a, center) - Dist (b, center);
> }
>
> main()
> {
> ...
> center.x = ...;
> center.y = ...;
> ...
> sort (...);
> ...
> }
>
> This type of solution has many problems.

int PtDistToCenterCmp( Pt const & a, Pt const & b, Pt const & center )
{
    return Dist (a, center) - Dist (b, center);
}

int main()
{
    sort( first, last, boost::bind( PtDistToCenterCmp, _1, _2, center ) );
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk