【发布时间】:2023-03-29 08:21:01
【问题描述】:
我对 2D 向量(或向量的向量)中的 C++ 移动语义有疑问。它来自动态规划的问题。为简单起见,我只以简化版为例。
//suppose I need to maintain a 2D vector of int with size 5 for the result.
vector<vector<int>> result = vector<vector<int>>(5);
for(int i = 0; i < 10; i++){
vector<vector<int>> tmp = vector<vector<int>>(5);
//Make some updates on tmp with the help of result 2D vector
/*
Do something
*/
//At the end of this iteration, I would like to assign the result by tmp to prepare for next iteration.
// 1) The first choice is to make a copy assignment, but it might introduce some unnecessary copy
// result = tmp;
// or
// 2) The second choice is to use move semantics, but I not sure if it is correct on a 2D vector.
// I am sure it should be OK if both tmp the result are simply vector (1D).
// result = move(tmp);
}
那么,是否可以简单地使用 `result = move(tmp);'二维向量的移动语义?
【问题讨论】:
-
在本例中,
result和tmp都将因超出范围而被销毁。因此,我们无法回答。给我们一个真实的例子,我们至少可以比较变量的寿命 -
std::move()在与矢量相同的情况下适用于二维矢量。你的result = std::move(tmp)应该没问题。 -
我不确定(你的解释有点短),但我认为你对“2D 矢量”这个想法太执着了。您的
tmp变量是某物的向量。那个“某物”恰好是另一个向量,但把它抽象掉了。向量被设计成可以在不知道它们持有什么类型的情况下使用。您的tmp变量是某物的向量。完毕。回到一维向量的世界。 -
如果您担心
move是否会递归到元素,那不会发生。vector的内容(通常是一对指针,或者一个指针和一个长度)被转移到另一个vector。 -
它可以帮助我将“2D 向量”视为某物的向量,它恰好是 int 的向量(by @JaMiT)。
标签: c++ vector move-semantics