在C++中遍歷unordered_map
的最佳實踐是使用迭代器進行遍歷。以下是一個示例代碼:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "apple"},
{2, "banana"},
{3, "orange"}
};
// 使用迭代器遍歷unordered_map
for(auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
在上面的示例中,我們首先使用unordered_map
初始化了一個myMap
對象,然后使用迭代器it
對myMap
進行遍歷,輸出每個鍵和值的內容。另外,也可以使用范圍for循環來遍歷unordered_map
,示例如下:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "apple"},
{2, "banana"},
{3, "orange"}
};
// 使用范圍for循環遍歷unordered_map
for(const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
無論是使用迭代器還是范圍for循環,都是遍歷unordered_map
的常見方法。具體選擇哪種方法取決于個人的偏好和需求。