首页 > 解决方案 > 如何在 C++ 中使用 unordered_maps 的 unordered_map?

问题描述

我有以下数据结构问题?你能帮帮我吗?所以我的要求是在我将新数据项添加到此映射中时将此数据结构初始化为默认值。

我怎样才能有效地做到这一点?

对于要添加的每个条目,我需要将 a1、a2、a3 设置为零。

struct a {
 int a1;
 int a2;
 int a3;
};

struct A {
 struct a A1;
 struct a A2;
};

unordered_map<int, unordered_map<int, struct A>> big_map;

尝试运行以下代码。

    unordered_map<int, struct A> inner_map;
    big_map[0] = inner_map;
    struct A m;
    big_map[0][0] = m;
    cout << "Values: " << big_map[0][0].A1.a1 << ", " << big_map[0][0].A1.a2 << ", " << big_map[0][0].A1.a3 << endl;

输出:

g++ -std=c++11 -o exe b.cc ./exe 值:0、0、1518395376 ./exe 值:0、0、-210403408 ./exe 值:0、0、-1537331360 ./exe 值: 0, 0, -915603664

所以没有为 a3 完成默认初始化?

标签: c++data-structuresunordered-map

解决方案


从 C++11 开始,您可以这样做:

struct a {
 int a1 = 0;
 int a2 = 0;
 int a3 = 0;
};

推荐阅读