C ++创建数组 [英] C++ creating arrays

查看:129
本文介绍了C ++创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能做这样的事情:

Why can't I do something like this:

int size = menu.size;
int list[size];

反正是有解决这个而不是使用矢量? (阵列的速度更快,所以我想用数组)

Is there anyway around this instead of using a vector? (arrays are faster, so I wanted to use arrays)

感谢

推荐答案

的大小必须在编译时是已知的,因为编译器需要知道多少的堆栈空间将需要的分配足够内存吧。 (编辑:我站在纠正在C, 可以在栈上分配变长数组C ++不允许变长数组,但是。)

The size must be known at compile-time, since the compiler needs to know how much stack space will be needed to allocate enough memory for it. ( I stand corrected. In C, variable length arrays can be allocated on the stack. C++ does not allow variable length arrays, however.)

不过,您可以创建在的堆阵列的在运行时:

But, you can create arrays on the heap at run-time:

int* list = new int[size];

只要确保你释放内存,当你做,否则你会得到一个内存泄漏:

Just make sure you free the memory when you're done, or you'll get a memory leak:

delete [] list;

请注意,它很容易意外创建内存泄漏和矢量几乎肯定更容易使用和维护。载体的非常的快(特别是如果你储备()他们到合适的规模第一),我强烈建议使用矢量代替人工记忆-management。

Note that it's very easy to accidentally create memory leaks, and a vector is almost for sure easier to use and maintain. Vectors are quite fast (especially if you reserve() them to the right size first), and I strongly recommend using a vector instead of manual memory-management.

在一般情况下,它是分析您的code,找出真正的瓶颈是不是一个好主意微优化前面(由于优化并不总是优化)。

In general, it's a good idea to profile your code to find out where the real bottlenecks are than to micro-optimize up front (because the optimizations are not always optimizations).

这篇关于C ++创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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