1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
#include <vector>
using distance_vec = std::vector< std::vector<double> > ;
double route_length( const std::vector<std::size_t>& route, const distance_vec& distance )
{
double length = 0 ;
// for each position i in the route up to the last but one position
for( std::size_t i = 0 ; i < (route.size()-1) ; ++i )
{
// add the distance between the location at this position
// and the location at the next position in the route
// note: we use at() rather than [] to defend against invalid data
length += distance.at( route[i] ).at( route[i+1] ) ;
}
return length ;
}
int main()
{
const std::vector< std::vector<std::size_t> > routes
{
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 },
{ 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 },
{ 0, 5, 4, 3, 2, 1, 9, 8, 7, 6, 0 },
{ 0, 5, 4, 3, 2, 1, 99, 8, 7, 6, 0 } // invalid route
};
const distance_vec distances
{
{ 0, 10.1843, 9.29856, 8.96788, 9.12499, 9.34745, 9.49533, 9.82055, 9.97055, 10.3772 },
{ 10.1843, 0, 14.1696, 14.6873, 14.5624, 14.4044, 14.3381, 14.1902, 14.2204, 14.0042 },
{ 9.29856, 14.1696, 0, 0.517772, 0.392882, 0.23489, 0.196771, 0.521997, 0.671996, 1.07866 },
{ 8.96788, 14.6873, 0.517772, 0, 0.15711, 0.379562, 0.527443, 0.852669, 1.00267, 1.40933 },
{ 9.12499, 14.5624, 0.392882, 0.15711, 0, 0.222452, 0.370333, 0.695559, 0.845558, 1.25222 },
{ 9.34745, 14.4044, 0.23489, 0.379562, 0.222452, 0, 0.147881, 0.473107, 0.623106, 1.02977 },
{ 9.49533, 14.3381, 0.196771, 0.527443, 0.370333, 0.147881, 0, 0.325226, 0.475225, 0.881889 },
{ 9.82055, 14.1902, 0.521997, 0.852669, 0.695559, 0.473107, 0.325226, 0, 0.149999, 0.556663 },
{ 9.97055, 14.2204, 0.671996, 1.00267, 0.845558, 0.623106, 0.475225, 0.149999, 0, 0.406664 },
{ 10.3772, 14.0042, 1.07866, 1.40933, 1.25222, 1.02977, 0.881889, 0.556663, 0.406664, 0 }
};
for( std::size_t i = 0 ; i < routes.size() ; ++i )
{
std::cout << "route #" << i+1 << " length == " ;
try { std::cout << route_length( routes[i], distances ) << '\n' ; }
catch( const std::out_of_range& ) { std::cout << " *** error: invalid route\n" ; }
}
}
|