C ++:什么是调整动态分配的数组的正确方法? [英] C++: What is the proper way of resizing a dynamically allocated array?

查看:140
本文介绍了C ++:什么是调整动态分配的数组的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,我会用做它的realloc

在C ++中,人们通常会考虑使用STL 矢量类。

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

但我怎么正确地调整C中的数组++不使用任何上述解决方案?

But how do I properly resize an array in C++ without using any of the above solutions?

推荐答案

的realloc 的C中没有良好的等价++。你需要手动复制阵列和复制旧的元素了。幸运的是,由于的std ::复制功能<算法> ,这是不是太糟糕了:

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 <algorithm>, 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;

希望这有助于!

编辑:重新排序的最后两行!哎呦!

Reordered the last two lines! Whoops!

这篇关于C ++:什么是调整动态分配的数组的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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