C++ 在固定时间内交换std::vector的内容-可能吗?
我正在使用C++ 在固定时间内交换std::vector的内容-可能吗?,c++,vector,stdvector,C++,Vector,Stdvector,我正在使用std::vector在图像类中存储图像。我在理解它们是如何工作的方面有点困难。旋转图像的函数: void Image :: resize (int width, int height) { //the image in the object is "image" std::vector<uint8_t> vec; //new vector to store rotated image // rotate "image" and store i
std::vector
在图像类中存储图像。我在理解它们是如何工作的方面有点困难。旋转图像的函数:
void Image :: resize (int width, int height)
{
//the image in the object is "image"
std::vector<uint8_t> vec; //new vector to store rotated image
// rotate "image" and store in "vec"
image = vec; // copy "vec" to "image" (right?)
//vec destructs itself on going out of scope
}
void Image::resize(整型宽度、整型高度)
{
//对象中的图像是“图像”
std::vector vec;//存储旋转图像的新向量
//旋转“图像”并存储在“vec”中
image=vec;//将“vec”复制到“image”(对吗?)
//vec在超出范围时自毁
}
有没有办法防止最后一次复制?就像在Java中,仅仅通过切换引用?如果阻止任何复制,那就太好了。您可以使用
std::vector::swap
:
image.swap(vec);
这本质上是一种指针交换,内容被传输而不是复制。它是完全有效的,因为您不关心交换后vec
的内容
在C++11中,您可以将vec
的内容“移动”到image
:
image = std::move(vec);
此操作基本上具有相同的效果,只是
vec
的状态定义不太明确(它处于自一致状态,但您不能对其内容进行任何假设……但您无论如何都不在乎,因为您知道您将立即丢弃它)。在C++11中,您可以这样做:image=std::move(vec)
。在C++03中,交换是一种方法。在固定时间内交换?谢谢,这就是我所需要的。@Bruce我添加了一个C++11选项。请注意,vec
的状态未指定,但有效。因此,我们可以从本质上clear()
向量,或者resize()
,并继续使用moved from对象。理论上,我们可能会认为,使用std::move
可能比swap
更快,因为它不需要关心源实例。