我有一个数据结构,它是unordered_map的unordered_map:
typedef std::unordered_map<string, int> map1;
typedef std::unordered_map<string, map1> map2;我想在map1中插入一个元素,而不需要使用if语句来检查它是否已经存在。但是,我有点困惑,因为除非已经有map1元素,否则map2没有值,但是map1元素来自map2 (如果它已经存在)。
做这件事最干净的方法是什么?
发布于 2015-12-23 00:44:07
如果您不使用指针,则可以在两个映射上简单地使用operator[]。
#include <iostream>
#include <unordered_map>
#include <string>
typedef std::unordered_map<std::string, int> map1;
typedef std::unordered_map<std::string, map1> map2;
int main()
{
map2 m2;
m2["a"]["b"] = 1;
std::cout << m2["a"]["b"] << std::endl;
}如果只有map2*的情况下,您可以执行以下操作
int main()
{
map2* m1 = new map2();
map2& m2 = *m1;
m2["a"]["b"] = 1;
std::cout << m2["a"]["b"] << std::endl;
}https://stackoverflow.com/questions/34420454
复制相似问题