在 C++ 中移动语义二维向量
move semantics 2d vector in C++
我对二维向量(或向量的向量)中的 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);' 可以吗?二维向量的移动语义?
是的,因为结果不是“二维”向量,它只是向量的一维向量。
我对二维向量(或向量的向量)中的 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);' 可以吗?二维向量的移动语义?
是的,因为结果不是“二维”向量,它只是向量的一维向量。