-2

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 に答える