What is the method for iterating through a map in C++?

In C++, iterators can be used to traverse a map. Here are several common traversal methods:

  1. Iterate using an iterator:
std::map<KeyType, ValueType> myMap;
// 向myMap中插入元素...

for(auto it = myMap.begin(); it != myMap.end(); ++it) {
    // 使用it->first访问键,使用it->second访问值
    std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
  1. Iterate using for loops (C++11 and above):
std::map<KeyType, ValueType> myMap;
// 向myMap中插入元素...

for(const auto& pair : myMap) {
    // 使用pair.first访问键,使用pair.second访问值
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
  1. Traverse using algorithms (C++11 and above):
std::map<KeyType, ValueType> myMap;
// 向myMap中插入元素...

std::for_each(myMap.begin(), myMap.end(), [](const std::pair<KeyType, ValueType>& pair){
    // 使用pair.first访问键,使用pair.second访问值
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
});

The above are three common methods for traversing a map, you can choose the suitable method according to specific needs.

bannerAds