C++:创建一个大小由用户输入的数组 [英] C++ : Creating an array with a size entered by the user
问题描述
我想知道我们是否可以创建一个用户指定大小的数组.
I was wondering if we can make an array with a size specified by the user.
例如:
int a;
cout<<"Enter desired size of the array";
cin>>a;
int array[a];
上述程序无法运行,因为数组大小必须是编译时常量,但在我的情况下,它是一个变量.
The above program won't work as array size has to be a compile-time constant but in my case, it is a variable.
是否可以将一个变量变成一个常量并赋值为一个数组的大小?
Is it possible to make a variable into a constant and assign it as size of an array?
推荐答案
在 C++ 中,有两种存储类型:基于堆栈的内存和基于堆的存储记忆.基于堆栈的内存中对象的大小必须是静态的(即不会改变),因此必须在编译时知道.这意味着你可以这样做:
In C++, there are two types of storage: stack-based memory, and heap-based memory. The size of an object in stack-based memory must be static (i.e. not changing), and therefore must be known at compile time. That means you can do this:
int array[10]; // fine, size of array known to be 10 at compile time
但不是这个:
int size;
// set size at runtime
int array[size]; // error, what is the size of array?
请注意,常量值与编译时已知值之间存在差异,这意味着您甚至不能这样做:
Note there is a difference between a constant value and a value known at compile time, which means you can't even do this:
int i;
// set i at runtime
const int size = i;
int array[size]; // error, size not known at compile time
如果你想要一个动态大小的对象,你可以使用某种形式的 new
操作符访问基于堆的内存:
If you want a dynamically-sized object, you can access heap-based memory with some form of the new
operator:
int size;
// set size at runtime
int* array = new int[size] // fine, size of array can be determined at runtime
但是,new
的这种原始"用法是不推荐的,因为您必须使用 delete
来恢复分配的内存.
However, this 'raw' usage of new
is not recommended as you must use delete
to recover the allocated memory.
delete[] array;
这很痛苦,因为您必须记住delete
使用new
创建的所有内容(并且仅delete
一次).幸运的是,C++ 有许多数据结构可以为您执行此操作(即它们在幕后使用 new
和 delete
来动态更改对象的大小).
This is a pain, as you have to remember to delete
everything you create with new
(and only delete
once). Fortunately, C++ has many data structures that do this for you (i.e. they use new
and delete
behind the scenes to dynamically change the size of the object).
std::vector
是这些自我管理数据结构的一个例子,是数组的直接替代品.这意味着你可以这样做:
std::vector
is one example of these self-managing data structures, and is a direct replacement for an array. That means you can do this:
int size;
// set size at runtime
std::vector<int> vec(size); // fine, size of vector can be set at runtime
并且不必担心new
或delete
.它变得更好,因为 std::vector
会在您添加更多元素时自动调整自身大小.
and don't have to worry about new
or delete
. It gets even better, because std::vector
will automatically resize itself as you add more elements.
vec.push_back(0); // fine, std::vector will request more memory if needed
总而言之:不要使用数组,除非你知道编译时的大小(在这种情况下,不要使用new
),而是使用std::vector
.
In summary: don't use arrays unless you know the size at compile time (in which case, don't use new
), instead use std::vector
.
这篇关于C++:创建一个大小由用户输入的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!