-4

How can I iterate through a hashMap (C++) so I can go through all the elements?

I have this hash named map:

HashMap<std::string, int> map;

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

    ...
    ...
    ...

map.insert (keyN, valueN);
Alonso
  • 141
  • 4
  • 12

2 Answers2

1

hash_map is deprecated, but the same principle applies... you can use a range loop (in this case with an unordered_map)

using auto will make it like:

#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;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

If it has both a begin() and end() member functions you should be able to simply put it in a range loop.

for (auto& entry : map)
    //whatever you want here
Jack Fenech
  • 108
  • 2
  • 7