简体   繁体   English

C ++分配数组语法问题

[英]c++ allocate array syntax question

You can write like this: 您可以这样写:

int test[] = {1,2,3,4};

but what if you want to use a pointer and allocate it with new? 但是,如果您想使用一个指针并将其分配给new怎么办?

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

This does not work, what is the syntax or is it possible? 这不起作用,语法是什么,或者可能吗?

This is one of the short-comings of current standard C++. 这是当前标准C ++的缺点之一。 Initialization is not uniform . 初始化不统一 Your best hope is uniform initialization in C++0x , but for the mean while you can assign the values after creating the array, eg 您最大的希望是在C ++ 0x中进行统一初始化 ,但同时您可以在创建数组后分配值,例如

int *test2;
test2 = new int[4]; // Note that you still have to specify the size in C++0x
test2[0] = 1;
test2[1] = 2;
test2[2] = 3;
test2[3] = 4;

If you compiler supports C++0x 如果编译器支持C ++ 0x

int *test2;
test2 = new int[4] {1,2,3,4}; // Initializer list in C++0x

would work. 会工作。 However you should always use std::vector instead of C style arrays while writing good C++ code. 但是,在编写良好的C ++代码时,应始终使用std::vector而不是C样式数组。

The first syntax is called aggregate initialization, and you cannot apply it to a dynamically allocated array. 第一种语法称为聚合初始化,您不能将其应用于动态分配的数组。 When allocating dynamically you must provide the number of elements that you want to initialize inside the square brackets and (optionally) the default value in parenthesis (if you want the array initialised). 动态分配时,必须在方括号内提供要初始化的元素数,并(可选)在括号中提供默认值(如果要初始化数组)。 The default value will be the same (if present) for all elements. 所有元素的默认值都相同(如果存在)。

You may want to look into the boost::assign library that may have support for this type of initialization (not sure). 您可能需要研究boost :: assign库,该库可能支持这种类型的初始化(不确定)。 Alternatively you can (at the cost of more code) do it yourself for POD types: 或者,您可以(以更多代码为代价)自己针对POD类型执行此操作:

int * array = new int[4];
{
   int values[] = { 1,2,3,4 };
   memcpy( array, values, sizeof(values) );
}

Or for non-pod types: 或对于非Pod类型:

type * array = new type[4];
{
   type values[] = { 1,2,3,4 }; // assuming type(int) constructor
   std::copy( values, values+4, array ); // better to use some magic to calculate size
}

At any rate both of those solutions require allocating locally and the copying (bit-size/c++) into the dynamically allocated memory. 无论如何,这两种解决方案都需要在本地分配以及将副本 (位大小/ c ++) 复制到动态分配的内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM