题解 | #合并表记录#c++利用两种不同map实现
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <iostream> #include <map> #include <unordered_map> using namespace std; void MergeSameIndex(unordered_multimap<int, int> umm)//unordered_multimap允许键值不唯一 { map<int, int> res; for (auto pair : umm) { //遍历原键值对,如果目标键值对中键不存在,就放入目标键值对 if (res.find(pair.first) == res.end()) { res.emplace(pair.first, pair.second); } else //如果存在,则在原来键值对的基础上,键不变,值相加 { res[pair.first] += pair.second; } } for (auto pair : res) { cout << pair.first << ' ' << pair.second << endl;; } } int main() { int n; cin >> n; unordered_multimap<int, int> umm; int key, value; for (int i = 0; i < n; i++) { cin >> key >> value; umm.emplace(key, value); } MergeSameIndex(umm); return 0; } // 64 位输出请用 printf("%lld")