Help with bool>operator

the question is change the operator overload <

it will return true if the total distance of the route represented by the first operand is smaller than the total distance represented by the second operand


I wrote the following code but it won't pass the unitest code
bool operator<(TrainRoute t)
{
int dist1=0;
for (int i = 0; i < t.nbOfStops-1; i++)
{
dist1=dist1+ t.distances[i];
}
int dist2=0;
for (int i = 0; i <t.nbOfStops-1; i++)
{
dist2=dist2+t.distances[i];
}
if (dist1 < dist2)

return true;
else
{
return false;
}


}


the rest of the exercise is:

class TrainRoute
{
private:
string departure;
string destination;

int nbOfStops;
//distances between stops
//it has nbOfStops-1 elements
int* distances;

char* trainCode;

public:
TrainRoute(string departure, string destination)
{
this->departure = departure;
this->destination = destination;
nbOfStops = 0;
this->distances = nullptr;
this->trainCode = nullptr;
}
The bool operator<(TrainRoute t) is part of TrainRoute right?

It is of course not correct since dist1 and dist2 are calculated exactly the same way. Remove t. within the loop for dist1:
1
2
3
4
5
int dist1=0;
for (int i = 0; i < t.nbOfStops-1; i++)
{
dist1=dist1+ t.distances[i];
}

chnaged the code sstill not working

bool operator<(TrainRoute t)
{
int dist1=0;
for (int i = 0; i <nbOfStops-1; i++)
{
dist1+=distances[i];
}
int dist2=0;
for (int i = 0; i <t.nbOfStops-1; i++)
{
dist2+=t.distances[i];
}
if (dist1 < dist2)

return true;
else
{
return false;
}


}
Have you implemented a proper copy constructor?
See Ganado's post here: http://www.cplusplus.com/forum/general/274582/#msg1185098

You're passing TrainRoute t to your operator by value.
This causes the compiler to make a shallow copy of TrainRoute.
You should be passing TrainRoute by const reference.
Note also that your operator should be a const function.
1
2
3
4
5
6
7
8
9
bool operator< (const TrainRoute & t) const
    {   int dist1 = 0;
        for (int i = 0; i <nbOfStops - 1; i++)
            dist1 += distances[i];
        int dist2 = 0;
        for (int i = 0; i <t.nbOfStops - 1; i++)
            dist2 += t.distances[i];
        return (dist1 < dist2);
    }


PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
This appears to be related to http://www.cplusplus.com/forum/general/274582/

It's garbage in / garbage out. The distances array almost certainly contains nbOfStops elements, not nbOfStops-1. Make sure that the distances array and nbOfStops is correct first. Only then can operator< hope to return the right result.
Topic archived. No new replies allowed.