In article <11*********************@g43g2000cwa.googlegroups. com>,
"Piotr" <ra************@gmail.com> wrote:
Is there a way to replace these binary function as well? I use them in
STL sort algorithm:
bool GreaterX::operator()( Rect* bd1, Rect* bd2)
{
return (bd1->getX() < bd2->getX());
}
bool SameX::operator()( Rect* bd1, Rect* bd2)
{
return (bd1->getX() == bd2->getX());
}
(I'm assuming getX returns an int.)
In both cases, the functions take two Rect*s, call "->getX()" on each
and performs a compare on the results returning a bool. The only
difference is what is being used to make the comparison.
It just so happens that there are two functors in the standard library
that already do the two different comparisons (std::less and
std::equal_to) so we simply need to create one class that can use either
of those functors. It's operator() will look something like this:
bool operator()( const Rect* bd1, const Rect* bd2 ) const {
return fn( bd1->getX(), bd2->getX() );
}
If 'fn' is std::less, then it will return true if bd1's x is less than
bd2's x. If 'fn' is std::equal_to, then the two xs must be equal for it
to return true.
Here is the whole class.
template <typename Op>
class compare_x_t: public binary_function<Rect*, Rect*, bool>
{
Op fn;
public:
compare_x_t() { }
compare_x_t( Op f ): fn( f ) { }
bool operator()( const Rect* bd1, const Rect* bd2 ) const {
return fn( bd1->getX(), bd2->getX() );
}
};
and a helper function for creating the right class object.
template <typename Op>
compare_x_t<Op> compare_x( Op f ) {
return compare_x_t<Op>( f );
}
Now you can:
void fn( list<Rect*>& ll, Rect* refRect ) {
ll.sort( compare_x( less<int>() ) );
list<Rect*>::iterator it = find_if( ll.begin(), ll.end(),
bind2nd( compare_x( equal_to<int>() ), refRect ) );
}
The above could be made more generic but don't do it unless you need it.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.