下面是我用C++编写的生成排序链表的类 当它不是模板时,完全相同的代码有效。 但是,一旦我进行了模板化,代码似乎无法正确比较变量。
例如, 当我插入 1, -1, 13 该列表应按递增顺序排列 -1 1 13。 然而,最终的名单是 13 -1 1。
调试的时候连最后一个case都没走。 当进入第二种情况时,说13小于-1。
发生了什么……?
template <class ItemType>
bool List342<ItemType>::Insert(ItemType *obj)
{
Node *insNode = new Node;
insNode->data = obj;
if (head == NULL)
{
head = insNode;
return true;
}
if (obj <= head->data)
{
insNode->next = head;
head = insNode;
return true;
}
Node *pNode = head;
while ((pNode->next != NULL) && ((pNode->next)->data <= obj))
{
pNode = pNode->next;
}
insNode->next = pNode->next;
pNode->next = insNode;
return true;
}
这里是节点定义
struct Node {
ItemType *data;
Node *next;
};
最佳答案
您的比较 (obj <= head->data)
和 ((pNode->next)->data <= obj)
显然在 ItemType *
之间指针。如果你想在 ItemType
之间进行比较他们指向的对象,您需要取消引用指针。例如,测试 (*obj <= *head->data)
.
关于c++ - 变量没有被正确比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26625609/