堆上数组的初始化 [英] Initialization of array on heap

查看:296
本文介绍了堆上数组的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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};

通过编译输出错误

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;

推荐答案

这很有趣:但是,如果这样做没有帮助,请尝试以下操作:

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(array, array + length, &stack_array[0]);

这篇关于堆上数组的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆