在以下情况下,我可以避免在 C++ 中复制 unordered_map 吗?
Can I avoid copying an unordered_map in C++ in the following situation?
上下文
我正在尝试使用 C++ 的动态规划算法来解决旅行商问题。我正在尝试解决 25 个城市的问题,这意味着我必须在每个 unordered_map
中存储多达 5 百万 key-value 对 迭代。
将此算法与 Python 和 4GB 内存一起使用我的进程由于内存不足而被终止,因此我正在尝试提高内存性能。
问题
为了减少使用的内存量,我尝试保留两个 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
(希望在常数时间内?),并释放内存已被旧 costs
使用,我将不再使用?
非常感谢任何帮助!谢谢!
-- 请随意编辑标题,使其更具描述性。找不到好的标题。
最好的做法是使用标准函数。当您使用 std 容器时,使用 std::move 或 std::swap 可能是解决问题的好方法。
上下文
我正在尝试使用 C++ 的动态规划算法来解决旅行商问题。我正在尝试解决 25 个城市的问题,这意味着我必须在每个 unordered_map
中存储多达 5 百万 key-value 对 迭代。
将此算法与 Python 和 4GB 内存一起使用我的进程由于内存不足而被终止,因此我正在尝试提高内存性能。
问题
为了减少使用的内存量,我尝试保留两个 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
(希望在常数时间内?),并释放内存已被旧 costs
使用,我将不再使用?
非常感谢任何帮助!谢谢!
-- 请随意编辑标题,使其更具描述性。找不到好的标题。
最好的做法是使用标准函数。当您使用 std 容器时,使用 std::move 或 std::swap 可能是解决问题的好方法。