-2

我正在尝试比较两个堆栈,看看它们是否相等。不幸的是,这段代码使得我所有的比较都说堆栈是相等的,即使堆栈不是。

Stack_implementation.cpp片段:

int DoubleStack::operator==(DoubleStack& rhs)
{
    int equal = 1;
    for (int i = 0; i <= tos; i++)         //tos is the top of the stack indicator
    {                                      //it tells how big the stack is
        if (data[i] != rhs.data[i])
        {
            equal = 0;
            break;
        }
    }
    return equal;
}

main.cpp相关片段:

{
    cout << "Comparing stacks..." << endl;
    if (stack1 == stack2)
        cout << "stack1 = stack2." << endl;
    else
        cout << "stack1 != stack2." << endl;
}

输出总是 stack1 = stack2

有谁知道怎么了?

4

1 回答 1

1

第一个检查应该是堆栈的大小;如果大小不同,则堆栈不能相等。编写的代码可以超出堆栈之一的末尾。

您也可以在找到一件不同的商品后立即退货。没有必要继续循环。

bool DoubleStack::operator==(DoubleStack& rhs)
{
    if (tos != rhs.tos) {
        return false;
    }

    for (int i = 0; i <= tos; i++)         //tos is the top of the stack indicator
    {                                      //it tells how big the stack is
        if (data[i] != rhs.data[i])
        {
           return false;
        }
    }
    return true;
}
于 2014-08-11T20:56:30.647 回答