2010-09-21 66 views
0

我有與操作員<一個問題,即我寫:問題的操作者<

在Node.h

. 
.. 
bool operator<(const Node<T>& other) const; 
const T& GetData(); 
. 
.. 
template <class T> 
const T& Node<T>::GetData() { 
return m_data; 
} 

template <class T> 
bool Node<T>:: operator<(const Node<T>& other) const 
{ 
return (*(this->GetData()) < *(other.GetData())); 
} 
在Heap.h

template<class T> 
void Heap<T>::Insert(Node<T>* newNode) { 
if (m_heap.size() == 0) { 
    m_heap.push_back(newNode); 
} 
else 
    DecreaseKey(newNode); 
} 

template<class T> 
void Heap<T>::DecreaseKey(Node<T>* newNode) { 
m_heap.push_back(newNode); 
int index = m_heap.size(); 
while ((index > 1) && (m_heap[(index/2)-1] < (m_heap[index-1]))) { // doen't do the operator < ! 
    Exchange(index,index/2); 
    index = index/2; 
} 
} 
在車輛

。 h:

bool operator< (const Vehicle& otherVehicle) const; 

在Vehi cle.cpp:

bool Vehicle::operator<(const Vehicle& otherVehicle) const { 
return (GetDistance() > otherVehicle.GetDistance()); 
} 
在main.cpp中

: 。

.. 
Node<Vehicle*> a(car1); 
Node<Vehicle*> b(car2); 
Heap<Vehicle*> heap; 
Node<Vehicle*>* p = &a; 
Node<Vehicle*>* q = &b; 
heap.Insert(p); 
heap.Insert(q); 
heap.ExtractMin()->GetData()->Show(); 
. 
.. 

爲什麼它不做競爭?與opeartor <,注意:它通過編譯器。

+0

請儘量使代碼儘量少。如果您在上述所有代碼中陳述問題,它會幫助閱讀很多內容。 – 2010-09-21 11:34:49

回答

1

因爲您使用了Vehicle *,而不是Vehicle。

+0

但我必須使用Vehicle *。 – 2010-09-21 10:48:22

+0

我如何使它與Vehicle *工作(該運營商<工作)? – 2010-09-21 10:49:16

+1

爲Vehicle *創建包裝類,然後存儲/比較它們。 – 2010-09-21 10:50:40

0

使用std :: priority_queue而不是Heap或任何允許定義自定義比較謂詞的其他堆。

+0

我必須創建teamplate堆... – 2010-09-21 11:00:47

+0

如果這是你的家庭作業,然後添加一個謂詞參數堆像std :: priority_queue有(看文檔)。否則,沒有理由使用自己的堆。 – ybungalobill 2010-09-21 11:12:58

0

從我看到m_heap商店指針節點

while ((index > 1) && (m_heap[(index/2)-1] < (m_heap[index-1]))) { // doen't do the operator < 

我想這應該做

while ((index > 1) && (*(m_heap[(index/2)-1]) < *(m_heap[index-1]))) { 
+0

好...現在做錯誤C662:「節點 ::的GetData」:不能轉換「這個」指針形式「常量節點」到「節點&」 – 2010-09-21 11:12:35

+0

與常量聲明的GetData =>「常量T&節點: :GetData()const「 – aeh 2010-09-21 11:36:44

+0

非常感謝你!!!!!! – 2010-09-21 12:00:31

3

m_heap是指針的容器。在這種情況下,應取消引用指針節點:

while ((index > 1) && (*m_heap[(index/2)-1] < (*m_heap[index-1]))) 

現在,這應該叫operator<爲節點,進而調用operator<的車輛。

0

簡答:不要使用指針。你可能不需要它們。

如果可能的話,如果使用普通對象,則更容易獲得這種類型的代碼。如果您需要使用指針的概念,請使用指針容器類,即一個作爲普通對象傳遞的包裝器,它具有值語義和潛在的自定義重載,例如您正在使用的運算符<,但隱藏內部實現指針。

這樣,你不需要在你的應用程序中處理指針,而只需要在語義相關的地方處理。