Boost logo

Boost :

From: Lois Goldthwaite (loisg_at_[hidden])
Date: 2000-05-27 05:54:57


Couldn't you just use reverse_iterators?

    sort( rbegin(), rend(), myCompare );

Lois

Joe Gottman wrote:

> Suppose you want to sort some objects using a custom ordering, so you create a binary comparison function myCompare. Later, you want to sort some more objects using the same comparison, but in the opposite order. The naive way of doing this is the following:
>
> sort(begin(), end(), not2(myCompare));
>
> Unfortunately, this will probably cause your computer to crash, because a predicate pred used in sorting must satisfy !(pred(x,y)) for all x and y. Obviously, if your predicate does this, not of your predicate will not. The correct way of reversing a comparison is to evaluate pred(y,x) instead of pred(x,y), see the canonical definition of x > y as y < x for an example.
>
> Here is a class that does just that. It simply takes a binary predicate and exchanges the order of the parameters. Please tell me what you think.
>
> #define EXCHANGE_PARAMETERS_H
> #include <functional>
> //This class reverses the order of parameters of a binary_function
> //object. Its most obvious use is to reverse the direction of a
> //comparison for sorting or STL sets, maps, etc.
> namespace boost {
> template <class OP>
> class exchange_parameters_t
> : public std::binary_function<typename OP::second_argument_type,
> typename OP::first_argument_type,
> typename OP::result_type>
> {
> private:
> OP op;
>
> public:
> exchange_parameters_t() : op() {};
> exchange_parameters_t(const OP &in_op) : op(in_op) {};
> typename OP::result_type operator()(
> const typename OP::second_argument_type &x1,
> const typename OP::first_argument_type &x2) const
> {return op(x2, x1);}
> };
>
> template <class OP>
> exchange_parameters_t<OP> exchange_parameters(const OP &op)
> {
> return exchange_parameters_t<OP>(op);
> }
>
> #endif
>
> [Non-text portions of this message have been removed]
>
> ------------------------------------------------------------------------
> Missing old school friends? Find them here:
> http://click.egroups.com/1/4055/3/_/9351/_/959391525/
> ------------------------------------------------------------------------


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