C++ 的 无序映射
等级 5312 次按键
unordered_map 用哈希表保存键值对。用 [] 赋值,用 find() == end() 检查键是否不存在,并遍历所有元素;遍历顺序没有规定,输出顺序可能与示例不同。
C++ 代码
// 从姓名映射到分数的哈希表1unordered_map<string, int> scores;// [] 在键不存在时先插入,再赋值2scores["Alice"] = 95;3scores["Bob"] = 87;4scores["Carol"] = 92;5 // 输出“Alice: 95”6cout << "Alice: " << scores["Alice"] << endl;7 // 键不存在时 find 返回 end()(与 [] 不同,不会添加元素)8if (scores.find("David") == scores.end()) { // 输出“David not found”9 cout << "David not found" << endl;10}11 // 用结构化绑定把每个元素拆成键和值12for (const auto& [name, score] : scores) { // 输出全部三项;顺序没有规定,可能不同13 cout << name << ": " << score << endl;14}运行结果
Alice: 95 David not found Carol: 92 Bob: 87 Alice: 95
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 19"× 16;× 7[× 5]× 5=× 5(× 4)× 4:× 3,× 2