如何给嵌套映射赋值

how assign values to a nested map

本文关键字:映射 赋值 嵌套      更新时间:2023-10-16

我有一个地图嵌套在另一个地图,我想分配值给外部地图,但我不太确定如何做到这一点。这使得程序在开始之前就达到收支平衡。当我通过

运行它时没有显示任何错误
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));

嗯,您的外部映射的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 } });

的缺点是它很难看,它甚至可能不是你想要的:最后一行没有效果,因为已经有一个键1的值,在这种情况下放置没有效果。如果您打算将条目{ 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);