C ++将映射复制到带有std :: move的矢量 [英] C++ copy map to vector with std::move

查看:52
本文介绍了C ++将映射复制到带有std :: move的矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对来说我是C ++的新手,这可能是一个愚蠢的问题,但是我现在试图理解 rValue lValue 引用,这涉及到我介意:

I'm relativly new to C++ and this might be a foolish question but I'm trying to understand rValue and lValue references at the moment and this came to my mind:

假设我们有一个地图(来自数据库等),我们希望将其所有值复制到向量中.

Let's say we have a map (which comes from a database or whatever) and we want to copy all values of it to a vector.

void insertItems(std::vector<std::string>& v)
{
    std::map<int, std::string> names = loadFromDb();

    for (auto& kv : names )
    {
        v.push_back(std::move(kv.second));
    }
}

在这里使用 std :: move 是否正确? std :: string 提供了一个移动构造函数,并且(也许不是用于字符串,而是用于更大的对象)该移动构造函数比复制构造函数快得多.我们也知道,我们不会在其他地方使用地图项,并且一旦离开函数,它们就会超出范围.那我的推定是对的吗?

Is it right to use std::move here? std::string provides an move constructor and (maybe not for string but for larger objects) the move constructor is much faster than the copy constructor. Also we know that we do not use the items of the map somewhere else and they go out of scope as soon as we leave the function. So is my presumption right?

我的思想中看不到矛盾,但这是一个复杂的话题,我害怕错过一些事情. P.S.:我认为问题名称不是最好的.如果您有更好的选择,请随时进行编辑.

I can't see a contradiction in my thoughts but it's a complicated topic and I'm afraid to miss something. P.S.: I think the question name is not the best. If you have a better one feel free to edit it.

推荐答案

是否使用 std :: move 在这里?

如果您确定将来不会访问已移动的值,则可以.

If you are sure that you won't access the moved values in the future, yes.

您可能还想使用 std :: vector :: reserve v 中预分配所需的空间.

You might also want to use std::vector::reserve to preallocate the required space in v.

v.reserve(v.size() + names.size());

这篇关于C ++将映射复制到带有std :: move的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆