I'm trying to sum up the distances of a closed path in some graph. The path, stored as a vector of int
s representing the nodes, begins with 0 and is supposed to have another edge back from the last node to 0. So I'm doing
using namespace std;
typedef vector<int> Route;
// r is some Route, g is some Graph
int distance = 0;
for (Route::iterator it = r.begin(); it != r.end(); ) {
clog << "it: " << *it << endl;
distance += g.dist(*it, (++it == r.end()) ? 0 : *it);
}
However, the first argument of my dist
method is receiving the wrong value. The logging in the line above does output the correct value, but logging the arguments from dist
shows that it does get passed the same value twice.
In the last iteration, it does get passed 0
which is plain wrong. Sometimes, with bigger vectors (I've got another input data with 120 waypoints), the first argument becomes some abstruse large value (which breaks the distance function) while the second argument is 0
(as supposed).
What does happen here and why does it happen? I have solved this now with a temporary variable for the first argument, but it seems ugly and unnecessary.
For completeness, here's the code of my dist
method which is part of a Graph
class (basically an adjacency matrix):
int dist(size_t x, size_t y) {
clog<<"distance: "<<x<<" "<<y<<endl;
if (x == y) return 0;
if (x < y) return dist(y, x); // edges are symmetric
if (x > size)
throw out_of_range("Graph::dist: index too large");
return triangle[x*(x-1)/2+y]; // stored in a flat array representing the lower half of the matrix
}
Here's the output for a small example (vector [0, 1, 2, 3]):
it: 0
distance: 1 1
it: 1
distance: 2 2
it: 2
distance: 3 3
it: 3
distance: 0 0
^^^ the distance arguments are wrong
and for the large example I'm getting
[…]
distance: 32 32
it: 32
distance: 51 51
it: 51
distance: 90 90
it: 90
distance: 12 12
it: 12
distance: 859381811 0
^^^^^^^^^ WTH?
terminate called after throwing an instance of 'std::out_of_range'
what(): Graph::dist: index too large
I had expected to get (for the small example):
it: 0
distance: 0 1
it: 1
distance: 1 2
it: 2
distance: 2 3
it: 3
distance: 3 0