2017-05-04 100 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