堆上数组的初始化

发布于 2024-10-10 01:17:23 字数 444 浏览 9 评论 0原文

如何手动初始化堆上数组中的值? 如果数组是局部变量(在堆栈中),则可以以非常优雅且简单的方式完成,如下所示:

int myArray[3] = {1,2,3};

不幸的是,以下代码

int * myArray = new int[3];
myArray = {1,2,3};

通过编译输出错误

error: expected primary-expression before ‘{’ token
error: expected `;' before ‘{’ token

我是否必须使用循环,或者像这样的不太优雅的方式这?

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

How do i manually initiate values in array on heap?
If the array is local variable (in stack), it can be done very elegant and easy way, like this:

int myArray[3] = {1,2,3};

Unfortunately, following code

int * myArray = new int[3];
myArray = {1,2,3};

outputs an error by compiling

error: expected primary-expression before ‘{’ token
error: expected `;' before ‘{’ token

Do i have to use cycle, or not-so-much-elegant way like this?

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

韵柒 2024-10-17 01:17:23

现在可以使用以下语法来完成此操作:

int * myHeapArray = new int [3] {1, 2, 3};

请注意,您必须将要分配的结构的大小与初始值设定项列表的大小相匹配。

由于我是在回答几年前发布的问题,因此值得一提的是,现代 C++ 不鼓励使用 new、delete 和本机(或裸)指针。相反,使用 std::unique_ptrstd::shared_ptr 等处理程序更受欢迎,因为它们会自动释放它们拥有的内存(检查 RAII 习惯用法)。

在这种特殊情况下,std::vector 将提供所有这些功能:堆分配数据、使用初始化列表(如 {1, 2, 3}),处理程序和移动语义等功能。

对于堆栈分配的数组,如果需要,可以考虑 std::array。

This can be accomplished today with the following syntax:

int * myHeapArray = new int [3] {1, 2, 3};

Notice you have to match the size of the structure you're allocating with the size of the initializer-list.

Since I'm replying to a question posted years ago, it is worth mentioning that modern C++ discourages the use of new, delete and native (or naked) pointers. The use of handlers such as std::unique_ptr and std::shared_ptr are favored instead, since they automatically release the memory they own (check RAII idiom).

In this particular case, std::vector would provide all such features: heap-allocated data, use of initializer-list (like {1, 2, 3}), handlers and move semantics among other features.

For stack-allocated arrays you can consider std::array, should you need them.

千柳 2024-10-17 01:17:23

这很有趣: 将数组推入向量

但是,如果这不适合您,请尝试以下操作:

#include <algorithm>
...


const int length = 32;

int stack_array[length] = { 0 ,32, 54, ... }
int* array = new int[length];

std::copy(stack_array, stack_array + length, &array[0]);

This is interesting: Pushing an array into a vector

However, if that doesn't do it for you try the following:

#include <algorithm>
...


const int length = 32;

int stack_array[length] = { 0 ,32, 54, ... }
int* array = new int[length];

std::copy(stack_array, stack_array + length, &array[0]);
橙幽之幻 2024-10-17 01:17:23

您可以定义常量数组,例如 myConstArray[] = {1, 2, 3} 并在 new int[3] 之后执行 memcpy 。

You can define constant array, like myConstArray[] = {1, 2, 3} and do memcpy after new int[3].

沒落の蓅哖 2024-10-17 01:17:23

{1,2,3} 是一种非常有限的语法,特定于 POD 结构初始化(显然 C 样式数组也被认为是一种语法)。你唯一能做的就是 int x[] = {1,2,3};int x[3] = {1,2,3}; ,但你不能同时执行 int x[3]; x={1,2,3}; 也不要在任何其他地方使用 {1,2,3}

如果您正在使用 C++,最好使用 std::vector 之类的东西而不是 C 风格的数组,因为它们被认为是危险的 - 例如,您无法知道它们的大小,并且必须使用 delete[ 删除它们],不是普通的删除。不过,使用 std::vector 您仍然会遇到相同的初始化问题。如果我经常使用这样的初始化,我很可能会创建一个分配给虚拟局部变量的宏,然后将内存复制到目的地。

编辑:您也可以这样做(std::vector 仍然更可取):

int* NewArray(int v1, int v2, int v3) { /* allocate and initialize */ }
int* p = NewArray(1,2,3);

但是您必须使用不同数量的参数覆盖该函数,或者使用 va_arg ,这又是不安全的。

EDIT2:我的答案仅对 C++03 有效,因为其他人提到 C++0x 对此有一些改进。

{1,2,3} is a very limited syntax, specific to POD structure initialization (apparently C-style array was considered one too). The only thing you can do is like int x[] = {1,2,3}; or int x[3] = {1,2,3};, but you can't do neither int x[3]; x={1,2,3}; nor use {1,2,3} in any other place.

If you are doing C++, it is preferable to use something like std::vector instead of C-style arrays, as they are considered dangerous - for example you can't know their size and must delete them with a delete[], not a normal delete. With std::vector you will still have the same initialization problem, though. If I used such initialization a lot, I would most probably create a macro assigning to a dummy local variable and then copying memory to the destination.

EDIT: You could also do it like this (std::vector still preferable):

int* NewArray(int v1, int v2, int v3) { /* allocate and initialize */ }
int* p = NewArray(1,2,3);

but then you'll have to override the function with different number of arguments, or use va_arg which is, again, unsafe.

EDIT2: My answer is only valid for C++03, as other people mentioned C++0x has some improvements to this.

单身情人 2024-10-17 01:17:23

C++0x 标准有一个名为 initializer_list 的特殊类型及其特殊语法(表达式 {1, 2, 3} 的类型为 std::initializer_list< ;int>)。 std::vectorstd::array 有其构造函数,因此您可以编写 vector; v = {1,2,3}

C++98/C++03中没有好的解决方案。

C++0x standard has the special type called initializer_list and the special syntax for it (type of expression {1, 2, 3} is std::initializer_list<int>). std::vector and std::array have constructors from it, so you can write vector<int> v = {1, 2, 3}.

There is no good solution in C++98/C++03.

遥远的绿洲 2024-10-17 01:17:23

如果您想要一个适用于所有类型的通用答案,那么您要做的是:

  1. malloc()或operator new()创建一个正确长度的未初始化存储数组,计算公式为nelts * sizeof(T)

  2. 创建一个由参数组成的数组每个元素的构造函数。

  3. 使用相应的参数将放置形式的构造函数应用于每个元素。

仅当相同的构造函数适用于每个元素时,这才有效。如果没有,您将需要更复杂的数据结构和算法来为每个元素选择正确的构造函数。

一种特殊情况是使用实际元素的数组并使用复制构造函数,一种特殊情况是当类型是 POD 时,您可以使用 memcpy 立即构造该批次。

如果构造函数采用两个参数,您将需要编写一个启动程序(包装器)。例如:

pair<double> init_data[] = {make_pair(1.0,0.0), make_pair(3.0,4.0)};
void init(void *p, pair<double> d) { new (p) complex(d.first, d.second); }

并使用它而不只是 new(p)。

If you want a general answer that works for all types, then what you do is:

  1. malloc() or operator new() to create an array of uninitialised storage of the right length, calculated by nelts * sizeof(T)

  2. Make an array consisting of the argument for a constructor for each element.

  3. Apply the constructor in placement form to each element using the corresponding argument.

This only works if the same constructor will do for every element. If not, you will need a more complicated data structure and algorithm to choose the right constructor for each element.

A special case of this is to use an array of the actual elements and use the copy constructor, and a special case of that is when the type is a POD and you can just use memcpy to construct the lot at once.

If the constructor takes two arguments, you will need to write an initiator procedure (wrapper). For example:

pair<double> init_data[] = {make_pair(1.0,0.0), make_pair(3.0,4.0)};
void init(void *p, pair<double> d) { new (p) complex(d.first, d.second); }

and use that instead of just new(p).

烟酒忠诚 2024-10-17 01:17:23

您还可以按如下方式初始化它:

int * myArray = new int[3];
*myarray=1;
*(myarray+1)=2;
*(myarray+2)=3;

You can also initialize it as follows:

int * myArray = new int[3];
*myarray=1;
*(myarray+1)=2;
*(myarray+2)=3;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文