如何打印嵌套std::unordered_map的内容?

How to print the content of a nested std::unordered_map?

我正在尝试打印这样指定的 std::unordered_map 的所有内容:

std::unordered_map<uint64_t, std::unordered_map<uint64_t,uint64_t>> m;

在地图中添加内容后,我尝试了以下操作:

for (auto it=map.begin(); it!=map.end(); it++) {
    cout << it->first << it->second << endl;
}

但它不起作用。

由于您嵌套了 std::unordered_map,因此应该可以执行以下操作:

for (auto const& i : m) {
    for (auto const& j : i.second) {
        std::cout << j.first << " " << j.second << std::endl;
    }
}

您还必须遍历嵌套地图。当您使用地图时,在结构化绑定之上使用基于范围的 for 会非常方便。为了避免这些神秘的 firstsecond 事情:

for (const auto& [key1, value1] : map)
    for (const auto& [key2, value2] : value1)
        std::cout << key2 << " " << value2 << std::endl;

虽然它只适用于 C++17。如果你不会用,那胡桃夹子给你答案。

How to print the content of a nested std::unordered_map?

打印嵌套 std::unordered_map use nested range-based for loop.

for (auto const& i: m) {
    std::cout << "Key: " << i.first << " (";
    for (auto const& j: i.second)
        std::cout << j.first << " " << j.second;
    std::cout << " )" << std::endl;
}

但是,如果您想修改容器的元素:

for (const& i: m) {
        for (const& j: i.second)
            // Do operations
}