C++: What is the proper way of resizing a dynamically allocated array?

后端 未结 4 783
谎友^
谎友^ 2021-01-03 01:59

In C, I would have done it using realloc.

In C++, one would normally consider using the STL vector class.

But how do I properly res

4条回答
  •  感动是毒
    2021-01-03 02:16

    There is no good equivalent of realloc in C++. You'll need to manually duplicate the array and copy the old elements over. Fortunately, thanks to the std::copy function in , this isn't too bad:

    size_t k =  /* ... */
    T* buffer = /* .. get old buffer of size k. .. */
    
    T* newBuffer = new T[newSize];  // Assume newSize >= k
    std::copy(buffer, buffer + k, newBuffer);
    
    delete [] buffer;
    buffer = newBuffer;
    

    Hope this helps!

    EDIT: Reordered the last two lines! Whoops!

提交回复
热议问题