C++ std::map of vectors
Collect parcels under their delivery route as each scan arrives.
A simple example
std::map of vectors
- Start with A already holds [1]
- Do this Append 2 in the A group
- Result A holds [1, 2]
Syntax
routes[key].push_back(parcel)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonGroup two parcels on one delivery route
A small courier sorts parcels into a list for each route. The first North parcel needs a new list, while the next North parcel should join that same list without erasing the first one.
#include <iostream>
#include <map>
#include <vector>
#include <string>
int main() {
std::map<std::string, std::vector<std::string>> routes;
for (const auto* parcel : {"P2", "P8"}) {
routes["North"].push_back(parcel);
}
const auto& north = routes.at("North");
std::cout << north[0] << ", " << north[1];
return 0;
}
P2, P8
Both parcels join the North route in scan order.
Fill the east-studio tote
A courier sorts parcels into destination totes as the labels arrive. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?
Prepare a library transfer
Three crates arrive for different branches at the sorting desk. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?
What to watch for
operator[] inserts a default-constructed vector for a new key. Use at for later reads that should never add a route.