Grouping with map of vectors
Completed
Read lines department name and print each department (sorted) with its names in input order.
Input
n, then n lines.
Output
One line per department: dept: a, b
Example
Input
5 sales zoe it amy sales bob hr cy it dan
Output
hr: cy it: amy, dan sales: zoe, bob
Editor
C++
Hints
groups[dept] creates an empty vector the first time.
Solution explanation
A map from key to vector is the standard grouping structure.
Show solution
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
map<string, vector<string>> groups;
for (int i = 0; i < n; i++) {
string dept, name;
cin >> dept >> name;
groups[dept].push_back(name);
}
for (const auto &[dept, names] : groups) {
cout << dept << ": ";
for (size_t i = 0; i < names.size(); i++) cout << names[i] << (i + 1 < names.size() ? ", " : "\n");
}
return 0;
}