map
-
Map就像C语言中的"字典"或"键值对数组",可以通过key快速找到value。
1.基本操作
#include <map> std::map<std::string, int> age; // 名字 -> 年龄 // 插入/修改(类似数组) age["Alice"] = 25; age["Bob"] = 30; age["Alice"] = 26; // 修改Alice的年龄 // 查找 if (age.count("Alice")) { // 检查key是否存在 printf("Alice的年龄: %d\n", age["Alice"]); } // 安全查找(不存在不会自动创建) auto it = age.find("Charlie"); if (it != age.end()) { printf("年龄: %d\n", it->second); // it->first是key, it->second是value } else { printf("Charlie不存在\n"); } // 删除 age.erase("Bob"); // 遍历 for (auto& pair : age) { printf("%s: %d岁\n", pair.first.c_str(), pair.second); }2.基本应用
场景1:计数器
// C语言风格:需要数组足够大 int count[1000] = {0}; count[num]++; // C++ map:不需要担心范围 std::map<int, int> count; count[num]++; // 自动初始化为0再加1 // 统计单词出现次数 std::map<std::string, int> wordCount; wordCount["hello"]++; wordCount["world"]++; wordCount["hello"]++; // hello: 2, world: 1场景2:映射关系
// 学生ID -> 成绩 map<int, int> scores; scores[1001] = 95; scores[1002] = 87; // 坐标 -> 属性 map<pair<int,int>,string> grid; grid[{0, 0}] = "起点"; grid[{10, 10}] = "终点";场景3:用字符串做key(C语言很难做)
// C语言:需要strcmp,很麻烦 // C++ map:直接用字符串 std::map<std::string, std::string> dict; dict["apple"] = "苹果"; dict["banana"] = "香蕉"; printf("%s\n", dict["apple"].c_str()); // 输出: 苹果

浙公网安备 33010602011771号