且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++:创建一个大小由用户输入的数组

更新时间:2023-11-10 07:51:45

在 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++ 有许多数据结构可以为您执行此操作(即它们在幕后使用 newdelete 来动态更改对象的大小).

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

并且不必担心newdelete.它变得更好,因为 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.