问题描述
在C ++ 11中,当我们想将值(破坏性地复制)移动到容器中时,可以使用 std :: move
来提高效率。
In C++11, we can get an efficiency boost by using std::move
when we want to move (destructively copy) values into a container:
SomeExpensiveType x = /* ... */;
vec.push_back(std::move(x));
但是我找不到其他方法。我的意思是这样的:
But I can't find anything going the other way. What I mean is something like this:
SomeExpensiveType x = vec.back(); // copy!
vec.pop_back(); // argh
这在适配器上更常见(复制弹出),例如堆栈
。可能存在这样的情况:
This is more frequent (the copy-pop) on adapter's like stack
. Could something like this exist:
SomeExpensiveType x = vec.move_back(); // move and pop
要避免复制?这已经存在吗?我在n3000中找不到类似的内容。
To avoid a copy? And does this already exist? I couldn't find anything like that in n3000.
我有种感觉,我很想念一些显而易见的东西(例如它的不必要),所以我为 ru dum做好了准备。 :3
I have a feeling I'm missing something painfully obvious (like the needlessness of it), so I am prepared for "ru dum". :3
推荐答案
在这里我可能完全错了,但不是您想要的
I might be total wrong here, but isn't what you want just
SomeExpensiveType x = std::move( vec.back() ); vec.pop_back();
假设SomeExpensiveType具有移动构造函数。 (当然,对于您的情况也是如此)
Assuming SomeExpensiveType has a move constructor. (and obviously true for your case)
这篇关于C ++“移出”容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!