std::map
时间: 2025-05-30 10:04:35 浏览: 21
### C++ `std::map` 使用方法及示例
#### 1. 简介
`std::map` 是 C++ 标准模板库(STL)中的一个关联容器,用于存储键值对。其内部实现基于红黑树,因此具有自动排序特性,并支持高效的插入、删除和查找操作[^2]。
---
#### 2. 基本用法
##### 2.1 定义和初始化
可以通过多种方式定义并初始化 `std::map`:
```cpp
#include <iostream>
#include <map>
int main() {
// 方式一:默认构造
std::map<int, std::string> map1;
// 方式二:通过初始列表构造
std::map<int, std::string> map2 = {{1, "one"}, {2, "two"}};
// 方式三:拷贝构造
std::map<int, std::string> map3(map2);
return 0;
}
```
---
##### 2.2 插入元素
可以使用以下几种方法向 `std::map` 中插入数据:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
// 方法一:使用下标运算符
myMap[1] = "apple";
// 方法二:使用 insert 函数
myMap.insert({2, "banana"});
myMap.insert(std::make_pair(3, "cherry"));
// 打印结果
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
---
##### 2.3 查找元素
可通过 `find()` 或下标运算符来访问特定键对应的值:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> fruitCount = {{"apple", 3}, {"banana", 5}};
// 使用 find()
auto it = fruitCount.find("apple");
if (it != fruitCount.end()) {
std::cout << "Found apple with count: " << it->second << std::endl;
}
// 使用下标运算符
std::cout << "Banana count: " << fruitCount["banana"] << std::endl;
return 0;
}
```
注意:如果使用下标运算符访问不存在的键,则会创建该键并将值设为默认值(对于整数类型,默认值为 0)。这可能会导致意外行为[^2]。
---
##### 2.4 删除元素
可利用 `erase()` 函数删除指定键或范围内的元素:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<char, int> charCounts = {{'a', 1}, {'b', 2}, {'c', 3}};
// 删除单个元素
charCounts.erase('b');
// 删除多个元素
charCounts.erase(charCounts.begin(), charCounts.find('c'));
for (const auto& pair : charCounts) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
---
#### 3. 常用函数详解
##### 3.1 大小与检查是否为空
- `size()` 返回当前映射中键值对的数量。
- `empty()` 判断映射是否为空。
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, double> data;
std::cout << "Size: " << data.size() << ", Empty: " << std::boolalpha << data.empty() << std::endl;
data[1] = 3.14;
std::cout << "Size after insertion: " << data.size() << ", Empty: " << data.empty() << std::endl;
return 0;
}
```
---
##### 3.2 遍历 `std::map`
可以通过迭代器或者基于范围的循环遍历整个映射:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}};
// 迭代器遍历
for (auto it = scores.begin(); it != scores.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 范围基遍历
for (const auto& [key, value] : scores) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
```
---
##### 3.3 统计键的数量
`count(key)` 可返回给定键是否存在及其数量(通常只为 0 或 1):
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> names = {{1, "John"}, {2, "Jane"}};
std::cout << "Key 1 exists? " << names.count(1) << std::endl;
std::cout << "Key 3 exists? " << names.count(3) << std::endl;
return 0;
}
```
---
##### 3.4 获取范围
`lower_bound()` 和 `upper_bound()` 提供了获取某个范围内键值的能力:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> numbers = {{1, "One"}, {2, "Two"}, {3, "Three"}};
// lower_bound
auto lb = numbers.lower_bound(2);
std::cout << "Lower bound of 2 is: " << lb->first << " -> " << lb->second << std::endl;
// upper_bound
auto ub = numbers.upper_bound(2);
std::cout << "Upper bound of 2 is: " << ub->first << " -> " << ub->second << std::endl;
return 0;
}
```
---
#### 4. 注意事项
- **自动排序**:`std::map` 默认按键升序排列,无法更改此顺序[^2]。
- **性能特点**:由于底层采用平衡二叉搜索树,插入、删除和查找的时间复杂度均为 O(log n)[^2]。
---
#### 5. 应用场景
适合需要按键有序存储且频繁执行查找操作的场合。例如,在统计单词频率时,可以用 `std::map` 存储每个单词及其出现次数[^4]。
---
阅读全文
相关推荐


















