我在重载比较运算符时遇到麻烦,以便以这种方式比较两个pair
结构:模拟类的重载比较运算符
typedef pair<string, unsigned int> INDEX;
bool operator>(INDEX &v1, INDEX &v2)
{
if(v1.second == v2.second) //if integer parts are equal
{
//string that comes earlier in the dictionary should be larger
return v1.first < v2.first;
}
return v1.second > v2.second;
}
实际比较发生在fixUp(CBTNODE hole)
fixUp(CBTNODE hole)
内,BinaryHeap
类的成员函数,它是派生类of CompleteBinaryTree
。 T
将被实例化为INDEX
类型,typedef
为pair<string, unsigned int>
。
换句话说,两对之间的比较:(“a.txt”,42)>(“b.txt”,42)应该返回true。
我试图以两种不同的方式在类声明之外重载operator>
,但它们都不起作用:
bool operator>(INDEX &v1, INDEX &v2);
bool operator>(BinaryHeap<T> &v1, BinaryHeap<T> &v2);
任何帮助将不胜感激!
Z.Zen
以下是声明:
typedef int CBTNODE;
template <typename T>
class CompleteBinaryTree {
public:
//Initializes an empty binary tree
CompleteBinaryTree(int initialSize = 10);
//Destructor
~CompleteBinaryTree();
//Returns the element of the CBT pointed to by node. Behavior is undefined
//if node does not exist.
T element(CBTNODE node);
protected:
T *data;
int numElts, maxElts;
};
typedef pair<string, unsigned int> INDEX;
template <typename T>
class BinaryHeap : public CompleteBinaryTree<T>
{
public:
//Maintain heap property with bottom up heapify method.
void fixUp(CBTNODE hole);
};
bool operator>(INDEX &v1, INDEX &v2);
实现:
template <typename T>
T CompleteBinaryTree<T>::element(CBTNODE node) {
assert(node >= 0);
assert(node < numElts);
return data[node];
}
template <typename T>
void BinaryHeap<T>::fixUp(CBTNODE hole)
{
T tmp = this->element(hole);
while(hole > 0 && this->element(hole/2) < tmp)
{
//do stuff
}
}
bool operator>(INDEX &v1, INDEX &v2)
{
if(v1.second == v2.second) //if two have same relevance
{
return v1.first < v2.first;
}
return v1.second > v2.second;
}
你得到了什么错误,并在该行? – Chubsdad 2010-10-25 05:41:49
是否真的需要定义'bool操作符'(INDEX&v1,INDEX &v2);'。不配对类是否有比较操作符? – Chubsdad 2010-10-25 05:44:09
它编译了但它没有做它应该做的事情。做比较:对<'a', 42>>对<'b', 42>,它返回false,根据我的定义,它应该返回true。该对的第一个元素是一个C++字符串,第二个元素是一个int。 – 2010-10-25 05:45:35