2010-10-25 69 views
0

我在重載比較運算符時遇到麻煩,以便以這種方式比較兩個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 CompleteBinaryTreeT將被實例化爲INDEX類型,typedefpair<string, unsigned int>

換句話說,兩對之間的比較:(「a.txt」,42)>(「b.txt」,42)應該返回true。

我試圖以兩種不同的方式在類聲明之外重載operator>,但它們都不起作用:

  1. bool operator>(INDEX &v1, INDEX &v2);
  2. 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; 
} 
+0

你得到了什麼錯誤,並在該行? – Chubsdad 2010-10-25 05:41:49

+0

是否真的需要定義'bool操作符'(INDEX&v1,INDEX &v2);'。不配對類是否有比較操作符? – Chubsdad 2010-10-25 05:44:09

+0

它編譯了但它沒有做它應該做的事情。做比較:對<'a', 42>>對<'b', 42>,它返回false,根據我的定義,它應該返回true。該對的第一個元素是一個C++字符串,第二個元素是一個int。 – 2010-10-25 05:45:35

回答

1

臨時,如element FUNC的結果,不能被綁定到一參考非const,例如您的operator>的正式參數。

聲明它正是如此:

bool operator>(INDEX const& v1, INDEX const& v2) 

但是,你目前的實現似乎並不爲operator>是正確的。

雖然我在這裏,但你想要的卻是operator<,因爲那是標準算法所要求的。也許再加上operator==(因爲從operator<合成它效率低)。有了這兩種關係,可以相對有效地檢查。

順便說一句,如果你停止使用ALL UPPERCASE命名所有其他的宏(參見FAQ),那麼你可以避免無意中與宏命名衝突。

乾杯&心連心,

+0

非常感謝你!它像一個魅力。我實際上實現了所有比較運算符,但爲了簡單起見,我只在我的問題中顯示了一個。 – 2010-10-25 07:21:24

+0

嗯。它沒有引起我關於'const'的提示,因爲OP提到代碼的構建和運行良好。 – Chubsdad 2010-10-25 07:59:03

1

不要的typedef INDEX,是明確的:

template<class F, class S> 
struct Index { 
    std::pair<F, S> Value; 
    Index(const std::pair<F, S>& pValue) 
    : Value(pValue) {} 
}; 

template<class F, class S> 
bool operator<(const Index<F, S>& pLeft, const Index<F, S>& pRight) { 
    // your implementation... 
}