C++“移出"容器

C++ quot;move fromquot; container(C++“移出容器)
本文介绍了C++“移出"容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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

这在适配器的 stack 上更为频繁(复制弹出).这样的事情是否存在:

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++“移出"容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)