2010-09-21 67 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

简答:不要使用指针。你可能不需要它们。

如果可能的话,如果使用普通对象,则更容易获得这种类型的代码。如果您需要使用指针的概念,请使用指针容器类,即一个作为普通对象传递的包装器,它具有值语义和潜在的自定义重载,例如您正在使用的运算符<,但隐藏内部实现指针。

这样,你不需要在你的应用程序中处理指针,而只需要在语义相关的地方处理。