【问题标题】:Can I avoid copying an unordered_map in C++ in the following situation?在以下情况下,我可以避免在 C++ 中复制 unordered_map 吗?
【发布时间】:2017-02-06 22:17:22
【问题描述】:

上下文

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

将此算法与 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; // ??
}

我不知道是否可以避免将所有 new_costs 复制到 costs,因为我们正在谈论 数百万 个元素。

我想知道是否可以使用指针使costs 指向new_costs,但在这种情况下,我不知道当我执行new_costs.clear(); 时会发生什么。

问题

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

非常感谢任何帮助!谢谢!

-- 随意编辑标题以使其更具描述性。我找不到合适的标题。

【问题讨论】:

  • std::swapstd::move 可能会有所帮助,如果我了解问题。

标签: c++ algorithm memory memory-management unordered-map


【解决方案1】:

最好的做法是使用标准函数。当您使用 std 容器时,使用 std::movestd::swap 可能是解决您问题的好方法。

【讨论】:

  • 谢谢。 std::swap 正是我想要的:)
  • @dgrcode:我认为std::move 是您正在寻找的。 costs = std::move(new_costs); new_costs.clear(); 是一个 O(1) 操作。
  • 使用std::movestd::swap 加上清除new_costs 有什么区别?移动速度更快吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2020-04-18
  • 2023-03-24
  • 2011-05-08
  • 2016-11-07
  • 1970-01-01
相关资源
最近更新 更多