Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2004-06-26 12:43:26


Nic Roets <cpp_at_[hidden]> writes:

> 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 (...);
> ...
> }
>

I think the Boost.Lambda library already provides what you want in a
way that's not sorting-specific:

  std::sort(first, last,
            bind(Dist, _1, center) < bind(Dist, _2, center));

Cheers,
Dave

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com

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