c++ 中 map 遍历
科技掌门 发布于:2024-01-17 12:19:58
在C++中,可以使用迭代器来遍历std::map容器中的键值对。以下是几种常见的遍历std::map的方法:
- 使用迭代器遍历std::map:
#include
#include
int main() {
map
// 使用迭代器遍历std::map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << \"Key: \" << it->first << \", Value: \" << it->second << endl;
}
return 0;
}
2. 使用范围-based for循环遍历std::map:
```cpp
#include
#include
- 使用auto关键字遍历std::map:
#include
#include
int main() {
map
// 使用auto关键字遍历std::map
for (auto pair : myMap) {
cout << \"Key: \" << pair.first << \", Value: \" << pair.second << endl;
}
return 0;
}
这些方法都可以用来遍历std::map容器中的键值对。根据具体需求,选择适合的遍历方法即可。