3

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

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));

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

4

1 回答 1

2

好吧,外部地图的 mapped_type 是map<int, int>,但您正在尝试使用pair<int, int>. 你可以尝试类似的东西

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

这样做的缺点是丑陋,甚至可能不是您想要的:最后一行没有效果,因为 key 已经有一个值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);
于 2015-07-31T01:01:44.450 回答