【问题标题】:How to print the content of a nested std::unordered_map?如何打印嵌套 std::unordered_map 的内容?
【发布时间】:2020-08-03 21:17:12
【问题描述】:

我正在尝试打印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;
}

但它不起作用。

【问题讨论】:

  • 您希望输出是什么样的?

标签: c++ c++11 stl unordered-map


【解决方案1】:

既然你已经嵌套了std::unordered_map,下面应该可以工作:

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

【讨论】:

  • @user13369031 很高兴我能帮上忙
【解决方案2】:

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

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

不过,它只适用于 C++17。如果你不能使用它,那么你有 NutCracker 的答案。

【讨论】:

    【解决方案3】:

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

    要打印嵌套的std::unordered_map,请使用嵌套的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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多