C++ 如何初始化一个大小最初未知的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22432755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:04:51  来源:igfitidea点击:

How to initialize an array whose size is initially unknown?

c++arraysinitializationlazy-initialization

提问by moonbeamer2234

Say I have this:

说我有这个:

int x;
int x = (State Determined By Program);
const char * pArray[(const int)x]; // ??

How would I initialize pArray before using it?Because the initial size of the Array is determined by user input

在使用之前如何初始化 pArray?因为 Array 的初始大小是由用户输入决定的

Thanks!

谢谢!

回答by herohuyongtao

Size of dynamically created array on the stack must be known at compile time.

在编译时必须知道堆栈上动态创建的数组的大小。

You can either use new:

您可以使用new

const char* pArray = new char[x];
...
delete[] pArray;

or better to use std::vectorinstead (no need to do memory management manually):

或者更好地使用std::vector(无需手动进行内存管理):

vector<char> pArray;
...
pArray.resize(x);

回答by Catskul

You cannot initialize an array at compile-time if you are determining the size at run-time.

如果在运行时确定大小,则不能在编译时初始化数组。

But depending on what you are trying to do, a non-const pointer to const data may provide you with what you're going for.

但是,根据您要执行的操作,指向 const 数据的非常量指针可能会为您提供所需的信息。

const char * pArray = new const char[determine_size()];

A more complete example:

一个更完整的例子:

int determine_size()
{
    return 5;
}

const char * const allocate_a( int size )
{
    char * data = new char[size];
    for( int i=0; i<size; ++i )
        data[i] = 'a';
    return data;
}

int main()
{
    const char * const pArray = allocate_a(determine_size());
    //const char * const pArray = new char[determine_size()];
    pArray[0] = 'b'; // compile error: read-only variable is not assignable 
    pArray    =  0 ; // compile error: read-only variable is not assignable 

    delete[] pArray;
    return 0;
}

I do agree with others that a std::vector is probably more what you're looking for. If you want it to behave more like your const array, you can assign it to a const reference.

我确实同意其他人的观点,即 std::vector 可能更符合您的要求。如果您希望它的行为更像您的 const 数组,您可以将其分配给一个 const 引用。

#include <vector>

int main()
{
    std::vector<char> data;
    data.resize(5);

    const std::vector<char> & pArray = data;

    pArray[0] = 'b'; // compile error: read-only variable is not assignable
}

回答by Freddy

The example you provided attempts to build the array on the stack.

您提供的示例尝试在堆栈上构建数组。

const char pArray[x];

However, you cannot dynamically create objects on the stack. These types of items must be known at compile time. If this is a variable based on user input then you must create the array in heap memory with the newkeyword.

但是,您不能在堆栈上动态创建对象。在编译时必须知道这些类型的项目。如果这是基于用户输入的变量,则必须使用new关键字在堆内存中创建数组。

const char* pArray = new char[x];

However, not all items need to be created on the heap. Heap allocation is normally a lot slower then stack allocation. If you want to keep your array on the stack you could always use block based initialization.

但是,并非所有项目都需要在堆上创建。堆分配通常比堆栈分配慢很多。如果您想将数组保留在堆栈上,您可以始终使用基于块的初始化。

#define MAX_ITEMS 100
const char pArray[MAX_ITEMS]

It should be noted that the second option is wasteful. Because you can not dynamically resize this array you must allocate a large enough chunk to hold the maximum number of items your program could create.

需要注意的是,第二种选择是浪费。因为你不能动态地调整这个数组的大小,所以你必须分配一个足够大的块来容纳你的程序可以创建的最大数量的项目。

Finally, you can always use data structures provide by C++. std::vector is such a class. It provides you a good level of abstraction and item are stored in contingent memory like an array. As noted by one of the other answers you should use the resize option once you know the final size of your vector.

最后,您始终可以使用 C++ 提供的数据结构。std::vector 就是这样一个类。它为您提供了良好的抽象级别,并且项目像数组一样存储在临时内存中。正如其他答案之一所指出的,一旦您知道矢量的最终大小,您就应该使用调整大小选项。

std::vector<char> pArray;
pArray.resize(X);

The reason for this is every time you add an element to a vector, if it no longer has enough room to grow, it has to relocate all items so they can exist next to one another. Using the resize method helps prevent vector from having to grow as you add items.

这样做的原因是每次向向量添加元素时,如果它不再有足够的增长空间,它必须重新定位所有项目,以便它们可以彼此相邻。使用调整大小方法有助于防止向量在添加项目时必须增长。