English 中文(简体)
C++: 如何妥善改造一个有活力的阵列?
原标题:C++: What is the proper way of resizing a dynamically allocated array?

在C,我将使用<代码>realloc。

在C++,通常考虑使用STLvector类别。

但是,我如何在C++中适当改变一个阵列,而不使用上述任何解决办法?

问题回答

在C++中,没有良好的<代码>realloc。 你们需要人工重复阵列,复制旧内容。 幸运的是,由于<代码>std:copy function in <algorithm>,该比例太差:

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;

希望这一帮助!

http://www.un.org。 重新排列最后两条路线! 谁!

做的是哪些病媒和真正的内力:形成一种新的、更大的阵容,复制旧的内容,摧毁旧的。

int* arr = new int[20];
...
//wanna resize to 25?
int* temp = new int[25];
std::copy(arr, arr+20, temp);
delete [] arr;
arr = temp;
... //now arr has 25 elements

但是,当然,你不应这样做:

如果您坚持在C++中进行这一分析,请<>可证明<>>> /em>大致如<代码>:查询/编码”进行,并利用全球新运营商分配原始记忆,然后使用新装置制造“已安装”物体。

否则,你将最终在你所分配的所有记忆中构筑物体,然后在你使用时分配物体。 除非您know:初始(违约)物体的构造是轻重,否则你会尽可能避免。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签