溫馨提示×

c++ map遍歷的方法是什么

c++
小億
181
2024-01-22 11:44:22
欄目: 編程語言

在C++中,可以使用迭代器來遍歷map。以下是幾種常見的遍歷方法:

  1. 使用迭代器遍歷:
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. 使用范圍for循環(huán)遍歷(C++11及以上):
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. 使用算法遍歷(C++11及以上):
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;
});

以上是三種常見的遍歷map的方法,可以根據(jù)具體的需求選擇適合的方法。

0