#include #include #include #include struct Destination { std::string name; int x, y; }; int distance_between(Destination const& d1, Destination const& d2) { return std::abs(d1.x - d2.x) + std::abs(d1.y - d2.y); } class Route_Planner { public: Route_Planner(Destination const& warehouse) : point_list {}, warehouse {warehouse} {} Route_Planner& operator+=(Destination const& d) { point_list.push_back(d); if (total_distance() > 100) { point_list.pop_back(); throw std::runtime_error("Med '" + d.name + "' blir den totala distansen större än vad en lastbil klarar av!"); } return *this; } Destination closest_destination(Destination const& remote) const { Destination closest { point_list[0] }; for (Destination const& d : point_list) { int dist1 {distance_between(d, remote)}; int dist2 {distance_between(closest, remote)}; if (dist1 < dist2) { closest = d; } } return closest; } int total_distance() const { int res {}; for (Destination const& d : point_list) { res += distance_between(d, warehouse) * 2; } return res; } std::string print() const { std::ostringstream oss {}; for (Destination const& p : point_list) { oss << p.name << ": [" << p.x << ", " << p.y << "]\n"; } return oss.str(); } private: std::vector point_list; Destination warehouse; }; std::ostream& operator<<(std::ostream& os, Route_Planner const& rhs) { return os << rhs.print(); } int main() { Route_Planner rp { Destination{"Erics lagerhus AB", 3, -2} }; try { rp += Destination{"willys", 10, 10}; rp += Destination{"coop", 3, -1}; rp += Destination{"hemköp", -8, 4}; rp += Destination{"lidl", -4, -5}; rp += Destination{"ica", 7, -5}; } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; } std::cout << "=== Alla butiker ===" << std::endl; std::cout << "# Total distans: " << rp.total_distance() << std::endl; std::cout << rp << std::endl; std::cout << "======" << std::endl; Destination car {"lastbil", -3, -2}; std::cout << "Närmaste butik är: " << rp.closest_destination(car).name << std::endl; return 0; }