Generic function objects

I have created a comparator which defines "ascending" order for a custom class. This can be used with standard functions such as std::sort() and std::find(). Now what if I want to reverse the comparison to "descending" order? Is there a standard function object wrapper which will reverse the order of the arguments sent to my comparator object? Similarly, are there wrapper classes to create other comparisons (such as "equality") so I don't have to implement them manually?

Thanks for your help.
Last edited on
Yes, std::rel_ops convert user-defined < into > and <= and >=.. er, you can't wrap that in a std::greater(), though, wrong namespace.

It's not all that hard to manually implement an op> which would simply return rhs<lhs;

You can't get equality from op<. You can only get equivalence (for which there is no standard wrapper)
Last edited on
> Is there a standard function object wrapper which will reverse the order of the arguments sent to my comparator object?

std::bind()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <algorithm>
#include <functional>

int main()
{
    int a[] = { 14, 32, 54, 34, 75, 86, 35, 25, 32, 65 } ;
    for( int v : a ) std::cout << v << ' ' ; std::cout << '\n' ;

    auto predicate = [] ( int a, int b ) { return a < b ; } ;
    std::sort( std::begin(a), std::end(a), predicate ) ;
    for( int v : a ) std::cout << v << ' ' ; std::cout << '\n' ;

    using namespace std::placeholders ;
    std::sort( std::begin(a), std::end(a), std::bind( predicate, _2, _1 ) ) ;
    for( int v : a ) std::cout << v << ' ' ; std::cout << '\n' ;
}
Thanks, Cubbi. std::rel_ops has exactly what I had in mind. I think a using statement would bring it into the global namespace if I needed to wrap it in std::greater(). I doubt I need to go that far, though, since I'll just pass it as the Comp parameter to functions such as std::sort().

Layne
@Layne a namespace using won't help: greater will look in std and will find the ton of op>'s defined there, and will never think to search the global namespace. Sorry for bringing your hopes up.

Topic archived. No new replies allowed.