map容器
0. Map (映射) / Multimap (多重映射) 容器介绍
头文件
// 头文件
#include <map> // 主要应用场景--键值对映射
- map 是一个关联容器,其中的元素是键值对,键和值都可以是任意类型。
- map 中的元素按照键的大小进行排序(默认升序)。
- multimap 与 map 的区别在于,multimap 允许键相同的元素存在。
1. Map/Multimap 容器的构造
默认构造
// 默认构造
map<int, string> myMap;
multimap<int, string> myMultimap;
拷贝构造和赋值
// 拷贝构造和赋值
map<int, string> map1;
map<int, string> map2;
map<int, string> map3(map1); // 拷贝构造
map2 = map1; // 赋值
// 交换
map1.swap(map2);
2. Map 容器的插入
// 插入元素
1. myMap[1] = "One";
2. myMap.insert(make_pair(3,"linmo")); //pair<int,string>(...)
3. myMap.insert(map<int,string>::value_type(1,"xiaomin"));
3. Map 容器的大小
// 返回容器中元素的个数
int size = myMap.size();
// 判断容器是否为空
bool isEmpty = myMap.empty();
4. Map 容器的删除
// 清除所有的元素
myMap.clear();
// 删除指定键的元素
myMap.erase(2);
5. Map 容器的排序
// 默认升序排列
map<int, string> map_A;
// 降序排列
map<int, string, greater<int>> map_B;
6. 自定义结构排序
struct Student {
int id;
string name;
};
struct CompareStudent {
bool operator()(const Student& a, const Student& b) const {
return a.id > b.id;
}
};
map<Student, int, CompareStudent> students;
7. Map 容器的查找
// 查找键为1的元素
auto it = myMap.find(1);
if (it != myMap.end()) {
// 元素存在
cout << "Value for key 1: " << it->second << endl;
} else {
// 元素不存在
cout << "Key 1 not found." << endl;
}
8. Pair 对组
// Pair 译为对组,可以将两个值视为一个单元
pair<int, string> keyValue(1, "One");
cout << "Key: " << keyValue.first << ", Value: " << keyValue.second << endl;
// Pair 在 map 中的应用
map<int, string> myMap2;
myMap2.insert(make_pair(3, "Three"));