我有一个问题,希望你知道答案。我有一个通用的堆类。让我们称之为 CHeap 。在这个类中,由于堆的性质,我需要比较组件(例如Heap[i]>Heap[j]
)。此处 堆 是 数组 。
如果我在 main.cpp 中定义了这样的变量:
cHeap <int> myHeap;
那时我没问题。但是如果我有数据结构,那就说:
struct S{
int data;
int code;
}
我定义:
cHeap <S> myHeap;
那时我有问题。例如,我希望比较为 代码 值。换句话说:Heap[i].code>Heap[j].code
但是,正如我之前所说,这是一个通用类,我不希望在我的代码中(在我的 CHeap 类中)。无论如何我可以在我的 main中重载 运算符&gt; CHeap 。 CPP ? 换句话说:
bool operator>(const S& s1, const s& s2){
return s1.code > s2.code;
}
在 main.cpp 中,并将其链接到 CHeap 类?
当我们使用STL的 * priority_queue * 时我们所做的事情:
priority_queue <S, vector <S>, greater <S> > myPQ;
bool operator>(const S& s1, const s& s2){
return s1.code > s2.code;
}
?!
由于
答案 0 :(得分:2)
您可以在operator>
结构中写下S
。
struct S{
int data;
int code;
bool operator>(const S& other) { ... }
}
您还可以在CHeap
课程中添加另一个模板参数,以便比较两个Type
:
template<typename T, typename Compare>
class CHeap
{
Compare comparer;
};
与价值使用comparer
进行比较:
if(comparer(object1, object2)) {} // If object1 is greater than object2
并写下你的Compare
论点:
class SComparer
{
public:
bool operator()(const S& s1, const s& s2) const { return s1.code > s2.code; }
}
答案 1 :(得分:1)
您可以定义S::operator>()
重载(这是一种常见做法)
struct S
{
int data;
int code;
bool operator>(const struct S & aux) const
{
return this->code > aux.code;
}
};
所以,你可以使用它:
if (Heap[i] >Heap[j])
{
......
}