将unordered_map设置为unordered_map的值

问题描述 投票:0回答:1

因此,我试图将unordered_map设置为另一个unordered_map的值。现在,我无法将值放入第二个unordered_map中。我的代码如下所示。

  std::string postCode;
  std::string[] postCodeSource = new std::string{1111,2222,3333,4444};
  std::unordered_map<std::string,unordered_map<int,Foo*>*> data;
  int k1=1234;//can be any number
  for(int i = 0; i < 4; i++){
    postCode = postCodeSource[i]
    if(data[postCode]==NULL) {
      data[postCode]=new std::unordered_map<int,Foo*>();
    }
    data[postCode]->at(int(k1)) = new Foo(postCodeSource[i]);
  }

课程:

class Foo{
  public:
  Foo();
  Foo(std::string postCode);
  std::string firstName,Customername,postCode;
}

Foo(std::string postCode);是一个简单的副本构造函数。

现在到达data[lastPlz.getString()]->at(int(k1.customer)) = new Foo(&k1);时,我从unordered_map到达异常范围,因为k1.customer上还没有对象!在更改代码之前,我创建并填充了一个像这样的指针。

std::unordered_map<int,Foo*> kdnrMap
kdnrMap[k1.customer] = new Foo(&k1);

后来我将kdnrMap添加到data。这将不再符合我的预期目的,因为此方法需要完全填充的[[kdnrMap,然后才能将其添加到无法再使用的[[data中。

所以我正在寻求帮助以填充kdnrMap,我已经尝试了很多我现在能想到的东西。
c++ unordered-map
1个回答
1
投票
std::unordered_map<std::string, std::unordered_map<int, std::unique_ptr<Foo>>> data; data[postCode][int(k1.Kundennr)] = new Foo(&k1);

我建议不要在此处使用原始指针,因为如果替换内部映射中的值,则存在泄漏内存的高风险。使用std::unique_ptr使处理指针变得非常简单。

您的异常可能会发生,因为unordered_map::at要求该值包含您要的键,以便检索对其映射的值的引用。如果像我的示例一样使用operator[],则如果找不到该键,则地图将创建一个条目。

如果您仍然坚持使外部映射的值成为内部映射的指针,则可以添加如下元素:

std::unordered_map<int, Foo*> &inner = *data[postCode]; inner[int(k1.Kundennr)] = new Foo(&k1);

data[postCode]->operator[](int(k1.Kundennr)] = new Foo(&k1);
© www.soinside.com 2019 - 2024. All rights reserved.