[英]Swap contents of std::vector in constant time - is it possible?
I'm using std::vector
to store an image in my Image class. 我正在使用
std::vector
在我的Image类中存储图像。 I'm having a bit trouble understanding how they work. 我理解他们的工作方式有点麻烦。 A function which rotates the image:
旋转图像的功能:
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
}
Is there any way to prevent the last copy? 有没有办法阻止最后一个副本? Like in Java, just by switching references?
就像在Java中一样,只需切换引用? It would be nice if any copying is prevented.
如果防止任何复制会很好。
You can use std::vector::swap
: 你可以使用
std::vector::swap
:
image.swap(vec);
This is a essentially a pointer swap, the contents are transferred rather than copied. 这本质上是指针交换,内容是传输而不是复制。 It is perfectly valid since you don't care about the contents of
vec
after the swap. 它完全有效,因为你不关心交换后
vec
的内容。
In C++11 you can "move" the contents of vec
into image
: 在C ++ 11中,您可以将
vec
的内容“移动”到image
:
image = std::move(vec);
This operation has essentially the same effect, except that the state of vec
is less well defined (it in a self consistent state but you cannot make any assumptions about its contents... but you don't care anyway because you know you are discarding it immediately). 这个操作具有基本相同的效果,除了
vec
的状态定义不太清楚(它处于自我一致状态但你无法对其内容做出任何假设......但是你无论如何也不在乎,因为你知道你在丢弃它立刻)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.