resize与push_back在std :: vector:它避免不必要的副本分配? [英] resize versus push_back in std::vector : does it avoid an unnecessary copy assignment?

查看:411
本文介绍了resize与push_back在std :: vector:它避免不必要的副本分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从 std :: vector 调用方法 push_back 时,其大小增加1,创建一个新的实例,然后你传递的参数将被复制到这个最近创建的元素,对吧?示例:

When invoking the method push_back from std::vector, its size is incremented by one, implying in the creation of a new instance, and then the parameter you pass will be copied into this recently created element, right? Example:

myVector.push_back(MyVectorElement());

那么,如果我想使用元素简单地使用默认值来增加向量的大小,不是更好地使用 resize 方法?我的意思是这样:

Well then, if I want to increase the size of the vector with an element simply using its default values, wouldn't it be better to use the resize method instead? I mean like this:

myVector.resize(myVector.size() + 1);

就我所见,这将完成完全相同的事情,但会避免完全不必要的分配复制元素的属性。

As far as I can see, this would accomplish exactly the same thing but would avoid the totally unnecessary assignment copy of the attributes of the element.

这个推理是否正确或者我缺少某些东西?

Is this reasoning correct or am I missing something?

推荐答案

至少用GCC,你使用哪个无关紧要(结果如下)。然而,如果你到达你必须担心它的点,你应该使用指针或(甚至更好)某种形式的智能指针。我当然会推荐提升库中的

At least with GCC, it doesn't matter which you use (Results below). However, if you get to the point where you are having to worry about it, you should be using pointers or (even better) some form of smart pointers.. I would of course recommend the ones in the boost library.

如果你想知道哪个更好在实践中使用,我建议 push_back reserve 作为resize将每次调用向量时调整向量大小,除非它与请求的大小相同。 push_back 并保留只会根据需要调整向量大小。这是一件好事,如果你想调整向量到 size + 1 ,它可能已经在 size + 20 ,因此调用resize不会提供任何好处。

If you wanted to know which was better to use in practice, I would suggest either push_back or reserve as resize will resize the vector every time it is called unless it is the same size as the requested size. push_back and reserve will only resize the vector if needed. This is a good thing as if you want to resize the vector to size+1, it may already be at size+20, so calling resize would not provide any benefit.

测试代码

#include <iostream>
#include <vector>

class Elem{
    public:
        Elem(){
            std::cout << "Construct\n";
        }
        Elem(const Elem& e){
            std::cout << "Copy\n";
        }
        ~Elem(){
            std::cout << "Destruct\n";
        }   
};


int main(int argc, char* argv[]){
    {
        std::cout << "1\n";
        std::vector<Elem> v;
        v.push_back(Elem());
    }

    {
        std::cout << "\n2\n";
        std::vector<Elem> v;
        v.resize(v.size()+1);
    }
}

测试输出 p>

Test Output

1
Construct
Copy
Destruct
Destruct

2
Construct
Copy
Destruct
Destruct

这篇关于resize与push_back在std :: vector:它避免不必要的副本分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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