我在重載比較運算符時遇到麻煩,以便以這種方式比較兩個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