交换或分配字符串向量更快? [英] Faster to swap or assign a vector of strings?

查看:61
本文介绍了交换或分配字符串向量更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字符串向量的类和一个分配给该向量的函数.我将函数更改为仅在成功的情况下才分配给向量.为此,我在函数中使用了字符串的临时向量,然后,如果函数成功,我将分配给类中的字符串的向量.

I have a class with a vector of strings and a function that assigns to that vector. I am changing my function to only assign to the vector if it's successful. To do that I use a temporary vector of strings in the function and then if the function is successful I assign to the vector of strings in the class.

例如:

class test
{
    vector<string> v;
    void Function()
    {
        vector<string> temp;
        v = temp; // Is this better?
        v.swap( temp ); // Or instead is this better?
    }
};

谢谢

推荐答案

在C ++ 11中,将其移动:

In C++11, move it:

v = std::move(temp);

在古老的方言中,交换比复制分配要好(假设向量不像您的示例中那样是空的).

In ancient dialects, swapping would be better than copy-assigning (assuming the vector isn't empty as it is in your example).

移动或交换只需要修改一些指针,而复制则需要分配内存和其他昂贵的技巧.

Moving or swapping just needs to modify a few pointers, while copying requires memory allocation and other expensive shenanigans.

这篇关于交换或分配字符串向量更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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