在下列情况下,我可以避免在C++中复制unordered_map吗?

Dan*_*ina 0 c++ memory algorithm memory-management unordered-map

上下文

我正在尝试使用C++的动态编程算法来解决旅行商问题.我试图解决25个城市的问题,这意味着我必须在每次迭代中存储多达500万个键值对. unordered_map

使用这个算法与Python和4GB ram我的进程由于内存不足而被杀死,所以我试图提高内存中的性能.

问题

为了减少使用的内存量,我试图保留两个unordered_set,一个具有前一个迭代的值,另一个具有新值.

std::unordered_map<std::string, int> costs;
std::unordered_map<std::string, int> new_costs;

for (int m = 1; m <= n; m++) {
  new_costs.clear();
  while (something) {
    // I build the content of new_costs based on the content of costs
  }

  // Here I want to make costs point to new_costs and free new_costs to
  // build the next iteration
  costs = new_costs; // ??
}
Run Code Online (Sandbox Code Playgroud)

我不知道是否可以避免复制所有内容new_costs,costs因为我们正在讨论数百万个元素.

我想知道我是否可以使用指针来costs指出new_costs,但在那种情况下我不知道当我这样做会发生什么new_costs.clear();.

总结我的问题是,我如何分配新内存new_costs,将内容放入new_costs内部costs(希望在恒定的时间?),并释放旧的已经使用的内存costs,我将不再使用?

任何帮助真的很感激!谢谢!

- 随意编辑标题,使其更具描述性.我找不到一个好头衔.

小智 5

最好的做法是使用标准功能.当您使用std容器时,使用std :: movestd :: swap可能是您的问题的一个很好的解决方案.