Choice between vector::resize() and vector::reserve()

后端 未结 4 1337
遥遥无期
遥遥无期 2020-11-22 05:01

I am pre-allocating some memory to my a vector member variable. Below code is minimal part

class A {
  vector t_Names;
public:
           


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:44

    resize() not only allocates memory, it also creates as many instances as the desired size which you pass to resize() as argument. But reserve() only allocates memory, it doesn't create instances. That is,

    std::vector v1;
    v1.resize(1000); //allocation + instance creation
    cout <<(v1.size() == 1000)<< endl;   //prints 1
    cout <<(v1.capacity()==1000)<< endl; //prints 1
    
    std::vector v2;
    v2.reserve(1000); //only allocation
    cout <<(v2.size() == 1000)<< endl;   //prints 0
    cout <<(v2.capacity()==1000)<< endl; //prints 1
    

    Output (online demo):

    1
    1
    0
    1
    

    So resize() may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back() new elements to it, the size() of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have used reserve() at the start to ensure there is already enough allocated memory, the size() of the vector will increase when you push_back() to it, but it will not allocate new memory again until it runs out of the space you reserved for it.

提交回复
热议问题