Show contents
Chapter 5 of 6 · 30 min
Project: managing a fleet of vehicles
By the end of this chapter, you'll be able to
- Create polymorphic objects from text with a factory function
- Turn conversion errors into exceptions with a clear message
- Isolate each invalid line without interrupting the processing
- Aggregate results with std::map for an ordered report
Step 1: the design
- The vehicles reuse the previous chapter's hierarchy.
- A factory function
make(line)reads a line such astruck;CD-456;8and returns the right object in astd::unique_ptr<Vehicle>, or throws an exception that explains the problem. - The vehicles are stored in a
std::map<std::string, std::unique_ptr<Vehicle>>, indexed by plate, to quickly find a trip's vehicle. - Each trip (
AB-123;120) adds its cost to the total of its vehicle's type. - Each line is processed in its own
try: an error never stops the following lines.
The trips are added up by type, in the map's alphabetical order.
Step 6 of 6
Text description of the animation
- A line of the vehicle list.
- The line is split into fields.
- The first field chooses the class; the load is converted to a number.
- A "plane" line throws an exception: it's reported, then we move on to the next one.
- The valid vehicles are stored in the fleet.
- The trips are added up by type, in the map's alphabetical order.
Step 2: the program
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
class Vehicle {
public:
explicit Vehicle(std::string plate) : plate_(std::move(plate)) {}
virtual ~Vehicle() = default;
virtual double cost_per_km() const = 0;
virtual std::string type() const = 0;
const std::string& plate() const { return plate_; }
private:
std::string plate_;
};
class Car : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.25; }
std::string type() const override { return "car"; }
};
class Truck : public Vehicle {
public:
Truck(std::string plate, double load_t) : Vehicle(std::move(plate)), load_t_(load_t) {}
double cost_per_km() const override { return 0.60 + 0.05 * load_t_; }
std::string type() const override { return "truck"; }
private:
double load_t_;
};
class Bike : public Vehicle {
public:
using Vehicle::Vehicle;
double cost_per_km() const override { return 0.0; }
std::string type() const override { return "bike"; }
};
std::vector<std::string> split(const std::string& line) {
std::vector<std::string> fields;
std::istringstream stream(line);
std::string field;
while (std::getline(stream, field, ';')) fields.push_back(field);
return fields;
}
double read_number(const std::string& text, const std::string& what) {
try {
std::size_t read = 0;
double value = std::stod(text, &read);
if (read == text.size() && value >= 0) return value;
} catch (const std::exception&) {
// stod failed: we throw our own message below
}
throw std::invalid_argument("invalid " + what + ": " + text);
}
std::unique_ptr<Vehicle> make(const std::string& line) {
auto f = split(line);
if (f.size() < 2) throw std::invalid_argument("incomplete line");
if (f[0] == "car") return std::make_unique<Car>(f[1]);
if (f[0] == "bike") return std::make_unique<Bike>(f[1]);
if (f[0] == "truck") {
if (f.size() != 3) throw std::invalid_argument("missing load");
return std::make_unique<Truck>(f[1], read_number(f[2], "load"));
}
throw std::invalid_argument("unknown type: " + f[0]);
}
int main() {
std::istringstream vehicles("car;AB-123\ntruck;CD-456;8\nbike;V-07\nplane;F-AAAA\ntruck;EF-789;abc\n");
std::istringstream trips("AB-123;120\nCD-456;300\nV-07;15\nZZ-000;50\nAB-123;80\n");
std::map<std::string, std::unique_ptr<Vehicle>> fleet;
std::string line;
int number = 0;
while (std::getline(vehicles, line)) {
++number;
try {
auto v = make(line);
std::string plate = v->plate();
fleet[plate] = std::move(v);
} catch (const std::exception& e) {
std::cout << "line " << number << " refused: " << e.what() << '\n';
}
}
std::cout << fleet.size() << " vehicles loaded\n";
std::map<std::string, double> byType;
while (std::getline(trips, line)) {
try {
auto f = split(line);
if (f.size() != 2) throw std::invalid_argument("badly formed trip: " + line);
auto it = fleet.find(f[0]);
if (it == fleet.end()) throw std::out_of_range("unknown vehicle " + f[0]);
const Vehicle& v = *it->second;
byType[v.type()] += read_number(f[1], "distance") * v.cost_per_km();
} catch (const std::exception& e) {
std::cout << "trip refused: " << e.what() << '\n';
}
}
double total = 0;
for (const auto& [type, cost] : byType) {
std::cout << type << ": " << cost << '\n';
total += cost;
}
std::cout << "total: " << total << '\n';
}
line 4 refused: unknown type: plane
line 5 refused: invalid load: abc
3 vehicles loaded
trip refused: unknown vehicle ZZ-000
bike: 0
car: 50
truck: 300
total: 350
The choices worth noticing:
- A factory, the only place that knows the types. The rest of the program only handles
Vehicles. Adding a scooter means one class and one line inmake. - Messages for humans.
std::stod("abc")throws an exception whose message is juststod.read_numbercatches it and replaces it withinvalid load: abc, much more useful in an error report. - One
tryper line. An error only concerns its own line; processing carries on. std::mapsorts its keys: the report always comes out in the same order.std::string plate = v->plate();copies the plate beforestd::move(v), in a separate statement: the order of operations is obvious, andvis no longer touched after the move.
Your turn
Worked exercise
Worked exercise: mileage per vehicle
We also want each vehicle's total mileage, sorted from largest to smallest. Write a function std::vector<std::pair<std::string, double>> ranking(const std::map<std::string, double>& km) that turns the map plate → km into a vector sorted by decreasing mileage, then by plate on a tie. With AB-123: 200, CD-456: 300, V-07: 15 and GH-321: 200, the expected order is CD-456, AB-123, GH-321, V-07.
Hint 1
A vector can be built directly from a map:
std::vector<std::pair<std::string, double>> v(km.begin(), km.end());.Hint 2
std::sort with a lambda: first compare a.second > b.second, then a.first < b.first if the mileages are equal.Show the solution and common mistakes
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
std::vector<std::pair<std::string, double>> ranking(const std::map<std::string, double>& km) {
std::vector<std::pair<std::string, double>> v(km.begin(), km.end());
std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) {
if (a.second != b.second) return a.second > b.second;
return a.first < b.first;
});
return v;
}
int main() {
std::map<std::string, double> km{{"AB-123", 200}, {"CD-456", 300}, {"V-07", 15}, {"GH-321", 200}};
for (const auto& [plate, distance] : ranking(km)) {
std::cout << plate << ": " << distance << " km\n";
}
}
CD-456: 300 km
AB-123: 200 km
GH-321: 200 km
V-07: 15 km
Common mistakes:
- Sorting only by mileage: AB-123 and GH-321 can then come out in any order, since
std::sortisn't stable. The second criterion makes the result reproducible. - Comparing with
>=in the lambda: a comparison function must be strict. With>=,std::sorthas undefined behaviour, and can even read outside the array.
Summary
- 1A factory function is the only place that knows the concrete classes.
- 2Turn a technical exception into a clear message for the user.
- 3One try per line isolates each error without stopping the processing.
- 4std::map keeps its keys sorted: the report is always in the same order.
- 5After std::move, the source object is empty: read what you need beforehand.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.