堆上数组的初始化
如何手动初始化堆上数组中的值? 如果数组是局部变量(在堆栈中),则可以以非常优雅且简单的方式完成,如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
现在可以使用以下语法来完成此操作:
请注意,您必须将要分配的结构的大小与初始值设定项列表的大小相匹配。
由于我是在回答几年前发布的问题,因此值得一提的是,现代 C++ 不鼓励使用 new、delete 和本机(或裸)指针。相反,使用
std::unique_ptr
和std::shared_ptr
等处理程序更受欢迎,因为它们会自动释放它们拥有的内存(检查 RAII 习惯用法)。在这种特殊情况下,
std::vector
将提供所有这些功能:堆分配数据、使用初始化列表(如{1, 2, 3}
),处理程序和移动语义等功能。对于堆栈分配的数组,如果需要,可以考虑 std::array。
This can be accomplished today with the following syntax:
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 asstd::unique_ptr
andstd::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.这很有趣: 将数组推入向量
但是,如果这不适合您,请尝试以下操作:
This is interesting: Pushing an array into a vector
However, if that doesn't do it for you try the following:
您可以定义常量数组,例如 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].
{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 仍然更可取):
但是您必须使用不同数量的参数覆盖该函数,或者使用 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 likeint x[] = {1,2,3};
orint x[3] = {1,2,3};
, but you can't do neitherint 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 normaldelete
. 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):
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.
C++0x 标准有一个名为
initializer_list
的特殊类型及其特殊语法(表达式{1, 2, 3}
的类型为std::initializer_list< ;int>
)。std::vector
和std::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}
isstd::initializer_list<int>
).std::vector
andstd::array
have constructors from it, so you can writevector<int> v = {1, 2, 3}
.There is no good solution in C++98/C++03.
如果您想要一个适用于所有类型的通用答案,那么您要做的是:
malloc()或operator new()创建一个正确长度的未初始化存储数组,计算公式为nelts * sizeof(T)
创建一个由参数组成的数组每个元素的构造函数。
使用相应的参数将放置形式的构造函数应用于每个元素。
仅当相同的构造函数适用于每个元素时,这才有效。如果没有,您将需要更复杂的数据结构和算法来为每个元素选择正确的构造函数。
一种特殊情况是使用实际元素的数组并使用复制构造函数,一种特殊情况是当类型是 POD 时,您可以使用 memcpy 立即构造该批次。
如果构造函数采用两个参数,您将需要编写一个启动程序(包装器)。例如:
并使用它而不只是 new(p)。
If you want a general answer that works for all types, then what you do is:
malloc() or operator new() to create an array of uninitialised storage of the right length, calculated by nelts * sizeof(T)
Make an array consisting of the argument for a constructor for each element.
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:
and use that instead of just new(p).
您还可以按如下方式初始化它:
You can also initialize it as follows: