在C++标准库中,std::map是一种关联式容器,用于存储具有唯一键的键值对,并根据键自动排序。它适合需要按关键字快速检索数据的场景。下面通过示例说明如何使用map完成插入、查找与删除这三种常见操作。

一、map的基础定义
使用map前需要包含头文件<map>,并通过std命名空间定义具体类型。例如下面的代码定义了一个键为int、值为string的map:
#include <iostream>
#include <map>
#include <string>
int main() {
// 定义键为int,值为string的map
std::map<int, std::string> studentMap;
return 0;
}
二、插入元素
map提供多种插入方式,最常用的是operator[]和insert方法。operator[]在键不存在时会自动创建,insert则可以避免覆盖已有值。
1. 使用operator[]插入
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> m;
// 使用[]插入或更新
m[1] = "Alice";
m[2] = "Bob";
// 若键已存在,会覆盖原值
m[1] = "Alicia";
return 0;
}
2. 使用insert插入
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> m;
// insert插入,键存在则不做改变
m.insert(std::make_pair(3, "Charlie"));
m.insert({4, "David"});
return 0;
}
三、查找元素
查找可以使用find成员函数或count成员函数。find返回迭代器,未找到时等于end();count返回键出现的次数,对于map只能是0或1。
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> m;
m[1] = "Alice";
m[2] = "Bob";
// 使用find查找
auto it = m.find(1);
if (it != m.end()) {
std::cout << "找到: " << it->second << std::endl;
}
// 使用count判断是否存在
if (m.count(2) > 0) {
std::cout << "键2存在" << std::endl;
}
return 0;
}
四、删除元素
删除操作一般通过erase完成,可以按迭代器、键或者区间删除。以下示例展示按键和按迭代器删除:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> m;
m[1] = "Alice";
m[2] = "Bob";
m[3] = "Charlie";
// 按键删除
m.erase(2);
// 按迭代器删除
auto it = m.find(1);
if (it != m.end()) {
m.erase(it);
}
// 遍历剩余元素
for (const auto& kv : m) {
std::cout << kv.first << ": " << kv.second << std::endl;
}
return 0;
}
五、小结
通过上述示例可以看出,C++的map在插入、查找与删除方面都提供了直观的接口。实际开发中建议根据是否需要覆盖已有值来选择insert或operator[],查找优先使用find以获得迭代器,删除时注意迭代器失效问题。熟练掌握这些操作能够提升代码可读性与运行效率。