Question

Ok I am creating a distance matrix of cities. Seeing as the distance would be the same either way you travel between cities I am storing the data in vector and using a special indexing system in order to access it so that I dont have to store the data twice. The issue is when I go to output the data the program segfaults which makes no sense.

Below is the part of the code that prints out from the distance matrix. The matrix size is 630. and the last index output to cout is 629 which should mean I am fine. Somehow it isn't. Any clues?

output << "DISTANCE table:\n";
output << "size = : " << distance_mat.size() << endl;
int ibase,iindex;
int k = 0;
for(int i = 0; i < distance_mat.size(); i++){
    for(int j = 0; j <= i; j++){
        ibase = i*(i+1)/2;
        iindex = ibase + j;
        output << setw(3) << right << i << " " << cities[i].Name << " to " << cities[j].Name << ": ";
        cout << iindex << " " << distance_mat.size() << endl;
        output << fixed << setprecision(2) << distance_mat[iindex] << " miles\n";
    }
}
cout << "ummmmmmm?" << endl;

output.close();

Ummmmm is never output and the last value printed doesnt even match what distance_mat[629] would be.

Was it helpful?

Solution

Supposingly distance_mat.size() = 630 then see the last iteration:

iindex = ibase + j = 629 * 630 / 2 = 198135

and then you try to access for j=0: distance_mat[iindex=198135] ... which you do not have... Something feels wrong with the algorithm.

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