Using custom std::set comparator

0 votes
asked Apr 12, 2010 by omry-yadan

I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can't get the following to compile with g++:


bool lex_compare(const int64_t &a, const int64_t &b) 
    stringstream s1,s2;
    s1 << a;
    s2 << b;
    return s1.str() < s2.str();

void foo()
    set<int64_t, lex_compare> s;

I get the following error:

error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’
error:   expected a type, got ‘lex_compare’

what am I doing wrong?

4 Answers

0 votes
answered Apr 12, 2010 by yacoby

You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

struct lex_compare {
    bool operator() (const int64_t& lhs, const int64_t& rhs) const {
        stringstream s1, s2;
        s1 << lhs;
        s2 << rhs;
        return s1.str() < s2.str();

You then use the class name as the type parameter

set<int64_t, lex_compare> s;

If you want to avoid the functor boilerplate code you can also use a function pointer (assuming lex_compare is a function).

set<int64_t, bool(*)(const int64_t& lhs, const int64_t& rhs)> s(&lex_compare);
0 votes
answered Apr 12, 2010 by potatoswatter

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    typedef std::set< T, ftor > t;

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

0 votes
answered Sep 15, 2017 by diraria

C++11 solution with lambda and without struct or function:

auto cmp = [](int a, int b) { return ... };
set<int, decltype(cmp)> s(cmp);


0 votes
answered Sep 15, 2017 by tom-whittock

You can use a function comparator without wrapping it like so:

bool comparator(const MyType &lhs, const MyType &rhs)
    return [...];

std::set<MyType, bool(*)(const MyType&, const MyType&)> mySet(&comparator);

which is irritating to type out every time you need a set of that type, and can cause issues if you don't create all sets with the same comparator.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter