Question

If anything in this code looks weird (like the illogical use of pointers) it's because it's for an assignment, so no need to let me know that there's absolutely no reason to use pointers in this situation. Thank you for you help in advance.

The code works for me except one thing, the insertNode function uses an overloaded < from the Pet class. this operator is supposed to compare the strings using the string.compare() function and return true or false based on the resulting value. However no sorting is done at all and the input file is just read in normally from beginning to end.

The problem is in the snippet below

bool  Pet::operator <(Pet &right)
{
    if (name.compare(right.name) < 0)
        return true;
    else if (name.compare(right.name) > 0)
        return false;
}

It seems to me that there is nothing wrong with this that would cause nothing to be changed. I haven't been able to test if the operators are right (> 0 and < 0) but i'm more concerned that it is doing nothing at all.

Was it helpful?

Solution

Your comparison function doesn't handle the case when the strings are equal.

bool  Pet::operator <(Pet &right)
{
    if (name.compare(right.name) < 0)
        return true;
    else if (name.compare(right.name) > 0)
        return false;
}

string.compare returns a negative value if it's less then it's argument, 0 when they are equal and a positive value when it's bigger. You don't handle the case when it returns 0 and it therefore falls off the end of the function which is undefined behavior.

Change the else if to:

else if (name.compare(right.name) >= 0)

@Benjamin is right, your whole function could be shortened down to:

bool  Pet::operator <(Pet &right)
{
    return name.compare(right.name) < 0
}

I somehow always oversee these things when answering questions...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top