通过hashmap c 迭代

Iterate through HashMap C++

本文关键字:迭代 hashmap 通过      更新时间:2023-10-16

如何通过hashmap(c (迭代以便我可以浏览所有元素?

我有这个命名地图:

HashMap<std::string, int> map;
map.insert (key1, value1);
map.insert (key2, value2);
map.insert (key3, value3);
    ...
    ...
    ...
map.insert (keyN, valueN);

hash_map已弃用,但是相同的原则适用...您可以使用范围循环(在这种情况下,使用 unordered_map (

使用Auto会像以下方式一样:

#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;
}

如果它具有begin((和end((成员函数,则应该可以简单地将其放在范围循环中。

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