阅读量:129
在C++中,可以使用迭代器来遍历map。以下是几种常见的遍历方法:
- 使用迭代器遍历:
std::map myMap;
// 向myMap中插入元素...
for(auto it = myMap.begin(); it != myMap.end(); ++it) {
// 使用it->first访问键,使用it->second访问值
std::cout << "Key: " << it>first << ", Value: " << it>second << std>
- 使用范围for循环遍历(C++11及以上):
std::map myMap;
// 向myMap中插入元素...
for(const auto& pair : myMap) {
// 使用pair.first访问键,使用pair.second访问值
std::cout << "Key: " << pair class="hljs-string">", Value: " << pair>
- 使用算法遍历(C++11及以上):
std::map myMap;
// 向myMap中插入元素...
std::for_each(myMap.begin(), myMap.end(), [](const std::pair& pair){
// 使用pair.first访问键,使用pair.second访问值
std::cout << "Key: " << pair class="hljs-string">", Value: " << pair>
以上是三种常见的遍历map的方法,可以根据具体的需求选择适合的方法。