c++ 遍历map,获取其中的key
时间: 2024-05-28 18:05:29 浏览: 146
以下是C++遍历map并获取其中的key的两种方式:
1. 使用迭代器遍历map并获取key:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// 使用迭代器遍历map并获取key
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
int key = it->first;
std::cout << "Key: " << key << std::endl;
}
return 0;
}
```
2. 使用C++11的范围-based for循环遍历map并获取key:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// 使用C++11的范围-based for循环遍历map并获取key
for (const auto& pair : myMap) {
int key = pair.first;
std::cout << "Key: " << key << std::endl;
}
return 0;
}
```
阅读全文