在自定义实现的数据结构中使用谓词



我有一个用于优先级队列应用程序的cusom实现的Heap

class Heap {
SomeCutsomClass elements[100];
....
....
};

现在我需要支持堆的keys之间的两种不同的比较操作,并且我想使用c++谓词来实现它

struct less1
{
bool operator()(const SomeCutsomClass& c1, const SomeCutsomClass& c1)
{
//specific implementation
}
};
struct less2
{
bool operator()(const SomeCutsomClass& c1, const SomeCutsomClass& c1)
{
//specific implementation
}
};

理想情况下,我应该能够在Heap的构造函数中以某种方式传递谓词

我无法想象如何实现这一目标
这并不是说我只想使用谓词。由于我不能在SomeCutsomClass中两次重载同一个运算符,所以我尝试使用谓词
我试着查找一些众所周知的数据结构(如std::sort等(的STL源代码,但它们对我来说很复杂。

这里有一个例子,包含std::less use和自定义谓词作为函数(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;
}

最新更新