【问题标题】:how assign values to a nested map如何为嵌套地图赋值
【发布时间】:2015-10-22 13:13:14
【问题描述】:

我有一个嵌套在另一个地图中的地图,我想为外部地图分配值,但我不太确定该怎么做。这会导致程序在开始之前就中断。我运行它时没有显示任何错误

map<int, map<int, int>> outer;
map<int, int> inner;


outer.emplace(1, make_pair(2, 1));
outer.emplace(2, make_pair(2, 1));
outer.emplace(3, make_pair(2, 1));

outer.emplace(1, make_pair(3, 1));

任何帮助都会有所帮助,谢谢

【问题讨论】:

    标签: c++ dictionary nested-map


    【解决方案1】:

    好吧,您的外部映射的 mapped_type 是 map&lt;int, int&gt;,但您正尝试使用 pair&lt;int, int&gt; 构建它。你可以试试

    outer.emplace(1, map<int,int>{ { 2, 1 } });
    outer.emplace(2, map<int,int>{ { 2, 1 } });
    outer.emplace(3, map<int,int>{ { 2, 1 } });
    
    outer.emplace(1, map<int,int>{ { 3, 1 } });
    

    它的缺点是丑陋,甚至可能不是您想要的:最后一行没有效果,因为键 1 已经有一个值,并且 emplace 在这种情况下没有效果.如果您打算将条目 { 3, 1 } 添加到第一个内部映射,这样它现在包含 { { 2, 1 }, { 3, 1 } },您可以改用以下构造,恕我直言,它看起来更好:

    outer[1].emplace(2, 1);
    outer[2].emplace(2, 1);
    outer[3].emplace(2, 1);
    
    outer[1].emplace(3, 1);
    

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2016-08-14
      • 1970-01-01
      • 2021-03-04
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 2021-07-15
      相关资源
      最近更新 更多