c++map遍历key
时间: 2025-03-16 20:05:35 浏览: 37
### C++ 中遍历 `map` 的 Key
在 C++ 中,可以通过多种方法来遍历 `std::map` 容器中的键(Key)。以下是几种常见的实现方式:
#### 使用迭代器遍历
可以利用 `std::map` 提供的迭代器访问其内部的每一个键值对。通过 `iter->first` 可以获取当前键。
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap = { {1, "one"}, {2, "two"}, {3, "three"} };
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << std::endl;
}
return 0;
}
```
此代码展示了如何使用传统的迭代器方式进行遍历[^2]。
---
#### 使用基于范围的 `for` 循环
自 C++11 起引入了基于范围的 `for` 循环语法,这种方式更加简洁直观。同样可以通过 `.first` 访问键。
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap = { {1, "one"}, {2, "two"}, {3, "three"} };
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << std::endl;
}
return 0;
}
```
在此示例中,推荐使用 `const auto&` 来避免不必要的拷贝操作,从而提高效率[^3]。
---
#### 将 Keys 存储到容器并排序
如果需要对 `map` 的键进行额外处理(如排序),可先将其提取至一个独立的容器(例如 `vector` 或其他序列容器)后再执行相应逻辑。
```cpp
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<int, std::string> myMap = { {3, "three"}, {1, "one"}, {2, "two"} };
// 创建用于存储 keys 的向量
std::vector<int> keys;
for (const auto& pair : myMap) {
keys.push_back(pair.first);
}
// 排序 keys 向量
std::sort(keys.begin(), keys.end());
// 输出已排序的 keys
for (const int& key : keys) {
std::cout << "Sorted Key: " << key << std::endl;
}
return 0;
}
```
上述代码片段演示了如何将 `map` 的键复制到一个单独的 `vector` 并对其进行排序[^1]。
---
阅读全文
相关推荐


















