c++stackcomparisonoverloadinglifo

Comparing Stacks of Doubles resulting in Always Equal


I'm trying to compare two stacks, to see if they are equal. Unfortunately, this code makes it so all of my comparisons say the stacks are equal, even if the stacks are not.

Stack_implementation.cpp snippet:

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 relevant snippet:

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

The output is always stack1 = stack2

Anyone know what's wrong?


Solution

  • The first check should be for the size of stacks; if sizes are not the same, stacks cannot be equal. The code as written can go beyond end of one of the stacks.

    You can also return as soon as you find one different item. There's no need to continue with the loop.

    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;
    }