Using predicates in custom implemented data structures
Here is an example containing both an example of std::less use and custom predicates as functions (lambdas).
#include <cassert>
#include <array>
#include <iostream>
#include <functional>
// Make heap a class template
// this allows you to specialize easily for any class
// I added the STL like third template parameter as example
// type_t is the type to store in the heap
// N is the size of the heap
template<typename type_t, std::size_t N, class Compare = std::less<type_t>>
class Heap
{
public:
using pred_t = std::function<bool(const type_t&, const type_t&)>;
Heap() :
m_predicate{ Compare() }
{
}
explicit Heap(pred_t predicate) :
m_predicate{ predicate }
{
}
bool compare(const int a, const int b)
{
return m_predicate(a, b);
}
private:
std::array<type_t, N> m_elements;
pred_t m_predicate;
};
struct SomeCustomClass
{
// all you need to make SomeCustomClass usable in Heap
// if it uses std::less as third template parameter
// is to provide this compare overload
bool operator<(const SomeCustomClass& other) const
{
return m_value < other.m_value;
}
int m_value{};
};
int main()
{
// this heap will use std::less
Heap<int, 100> less_heap;
assert(less_heap.compare(1, 2));
// create a lambda predicate
auto pred = [](const int& lhs, const int& rhs)
{
return lhs > rhs;
};
// this heap will use custom predciate
Heap<int, 100> greater_heap(pred);
assert(greater_heap.compare(2,1));
//
Heap<SomeCustomClass, 10> custom_heap;
return 0;
}