2017-05-04 99 views
-4

如何遍歷hashMap(C++),以便可以遍歷所有元素?通過HashMap迭代C++

我有這個哈希命名地圖:

HashMap<std::string, int> map; 

map.insert (key1, value1); 
map.insert (key2, value2); 
map.insert (key3, value3); 

    ... 
    ... 
    ... 

map.insert (keyN, valueN); 
+0

你試過了什麼?它不應該與任何其他容器有所不同。 – NathanOliver

+0

[如何通過映射的C++映射循環?](http://stackoverflow.com/questions/4844886/how-to-loop-through-ac-map-of-maps) – Borgleader

+0

'HashMap' is不是C++的一部分。如果您正在使用第三方庫,則需要研究其文檔。 –

回答

0

hash_map已被棄用,但同樣的原則也適用...你可以使用一系列循環(在這種情況下,與unordered_map

使用自動會使它像:

#include <iostream> 
#include <string> 
#include <unordered_map> 
int main() 
{ 
    std::unordered_map<std::string, int> myMap; 

    myMap.insert(std::pair<std::string, int>("a", 1)); 
    myMap.insert(std::pair<std::string, int>("b", 2)); 
    myMap.insert(std::pair<std::string, int>("c", 3)); 
    myMap.insert(std::pair<std::string, int>("d", 4)); 
    for (const auto& x : myMap) 
    { 
     std::cout << "fisrt: " << x.first << ", second: " << x.second << std::endl; 
    } 
    std::cin.get(); 
    return 0; 
} 
0

如果它有一個begin()和end()成員函數,你應該能夠簡單地p在範圍循環中進行。

for (auto& entry : map) 
    //whatever you want here