Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to create comparer for objects behind pointers

I use data structures, and I sort these data structures a lot. These data structures are holding pointers to objects, not directly the objects themselves. Now I can write a simple comparison functor, or function, to tell the sort algorithm how to sort the pointers:

struct Object_ptr_comparer {
    bool operator()(const Object* first, const Object* second) {
        return *first < *second;
    }
};

And use for example std::sort:

Object_ptr_comparer comp;
std::sort(data_str.begin(), data_str.end(), comp);

The only problem with this solution that I have to write extra pointer comparator functor for any type of class. Yes, I could use inheritance and polymorphism to write only the comparator of some root class, but I don't want to. Is there any other smart way to do this?

like image 950
WonderCsabo Avatar asked Jan 30 '26 08:01

WonderCsabo


2 Answers

What about a template?

struct ptr_comparer {
    template<typename T>
    bool operator()(const T* first, const T* second) {
        return *first < *second;
    }
};

used like this:

std::sort(data_str.begin(), data_str.end(), ptr_comparer());
like image 62
Baptiste Wicht Avatar answered Feb 01 '26 22:02

Baptiste Wicht


That's what templates are for!

struct ptr_comparer {
    template<class Object>
    bool operator()(const Object* first, const Object* second) const {
        return std::less<Object>()(*first, *second);
    }
};

std::sort(data_str.begin(), data_str.end(), ptr_comparer());

Since I've templated the operator rather than specializing the comparer directly, the compiler can deduce the types, so we don't have to put the types directly.

I use std::less rather than operator<, because it safely compares pointers to pointers (like char**), rather than relying on Undefined Behavior. std::less falls back on operator<, so it doesn't add any complexity to calling code, and there should be no downside.

I'm certain this one compiles

like image 40
Mooing Duck Avatar answered Feb 01 '26 22:02

Mooing Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!