【发布时间】: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::swap或std::move可能会有所帮助,如果我了解问题。
标签: c++ algorithm memory memory-management unordered-map