题解 | 合并表记录
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <iostream> #include <map> using namespace std; int main() { int n; cin >> n; // 读取记录数 // 使用 map 来存储索引和对应的数值 // map 会自动按照索引从小到大排序 map<int, int> record; // 读取 n 条记录 for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; // 读取索引和数值 record[x] += y; /* 合并相同索引的记录,record[x] 是 map 的访问操作符,用于访问键为 x 的值。它的行为如下:如果键 x 已经存在于 map 中,record[x] 返回对应的值的引用。 如果键 x 不存在,map 会自动插入一个新的键值对,键为 x,值为默认值(对于 int 类型,默认值是 0),然后返回这个新值的引用。*/ } // 输出合并后的结果 for (const auto& pair : record) { cout << pair.first << " " << pair.second << endl; } return 0; }