Faster to swap or assign a vector of strings?

只谈情不闲聊 提交于 2019-12-20 04:11:58

问题


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.

For example:

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

Thanks


回答1:


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.




回答2:


From the complexity point of view std::swap algorithm should be preferred.

vector<string> temp;
v = temp;           // complexity is linear in the size of the temp
v.swap( temp );     // complexity is constant


来源:https://stackoverflow.com/questions/22001854/faster-to-swap-or-assign-a-vector-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!