unordered_map是无序的容器,它不会保留插入顺序,所以要定义一个vector来存储输入的顺序 不算难
#include <iostream> #include <unordered_map> #include <vector> using namespace std; int main() { int n, m; cin >> n; unordered_map<string, int> candidates; vector<string> candidates_order; for(int i = 0; i < n; ++i) { string name; cin >> name; candidates.insert({name, 0}); candidates_order.push_back(name); } cin >> m; int count_invalid = 0; while(m--) { string name; cin >> name; if(candidates.find(name) != candidates.end()) { ++candidates[name]; } else ++count_invalid; } for(const auto& name: candidates_order) { cout << name << " : " << candidates[name] << endl; } cout << "Invalid : " << count_invalid << endl; return 0; }