doc/notebook/docs/C++/8.map.md

69 lines
2.1 KiB
Markdown
Raw Normal View History

1. **构造函数**
- `map()`:创建一个空的映射容器。
- `map(const map& other)`:拷贝构造函数,用另一个映射容器初始化当前映射容器。
2. **赋值和交换**
- `operator=`:将一个映射容器赋值给另一个映射容器。
- `assign`:用特定数量的键值对或范围内的键值对替换映射容器的内容。
- `swap`:交换两个映射容器的内容。
3. **迭代器相关**
- `begin`:返回指向第一个键值对的迭代器。
- `end`:返回指向最后一个键值对之后的位置的迭代器。
4. **容量**
- `empty`:判断映射容器是否为空。
- `size`:返回映射容器中键值对的数量。
- `max_size`:返回映射容器最大可容纳的键值对数量。
5. **插入和访问元素**
- `insert`:插入一个键值对或多个键值对。
- `erase`:移除指定键或范围内的键值对。
- `clear`:移除映射容器的所有键值对。
- `find`:查找指定键的迭代器。
- `operator[]`:访问映射容器中指定键对应的值。
6. **其他操作**
- `count`:返回指定键在映射容器中出现的次数。
- `lower_bound`:返回第一个不小于指定键的迭代器。
- `upper_bound`:返回第一个大于指定键的迭代器。
```cpp
#include <iostream>
#include <map>
using namespace std;
int main() {
// 创建空映射容器
map<int, string> mymap;
// 插入键值对
mymap.insert(pair<int, string>(1, "One"));
mymap.insert(make_pair(2, "Two"));
mymap[3] = "Three";
// 访问元素
cout << "Value at key 2: " << mymap[2] << endl;
// 查找元素
map<int, string>::iterator it = mymap.find(3);
if (it != mymap.end()) {
cout << "Key 3 found, value: " << it->second << endl;
}
// 移除键值对
mymap.erase(2);
// 输出键值对数量
cout << "Size of map: " << mymap.size() << endl;
// 遍历输出所有键值对
for (auto& pair : mymap) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
return 0;
}
```