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;
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)
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
booloperator< (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.
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.