开发者

Is there a way to statically-initialize a dynamically-allocated array in C++?

In C++, I can statically initialize an array, e.g.:

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

Is there an easy way to initia开发者_如何学运维lize a dynamically-allocated array to a set of immediate values?

int *p = new int[3];
p = { 1, 2, 3 }; // syntax error

...or do I absolutely have to copy these values manually?


You can in C++0x:

int* p = new int[3] { 1, 2, 3 };
...
delete[] p;

But I like vectors better:

std::vector<int> v { 1, 2, 3 };

If you don't have a C++0x compiler, boost can help you:

#include <boost/assign/list_of.hpp>
using boost::assign::list_of;

vector<int> v = list_of(1)(2)(3);


You have to assign each element of the dynamic array explicitly (e.g. in a for or while loop)

However the syntax int *p = new int [3](); does initialize all elements to 0 (value initialization $8.5/5)


To avoid endless push_backs, I usually initialize a tr1::array and create a std::vector (or any other container std container) out of the result;

const std::tr1::array<T, 6> values = {T(1), T(2), T(3), T(4), T(5), T(6)};
std::vector <T> vec(values.begin(), values.end());

The only annoyance here is that you have to provide the number of values explicitly.

This can of course be done without using a tr1::array aswell;

const T values[] = {T(1), T(2), T(3), T(4), T(5), T(6)};
std::vector <T> vec(&values[0], &values[sizeof(values)/sizeof(values[0])]);

Althrough you dont have to provide the number of elements explicitly, I prefer the first version.


No, you cannot initialize a dynamically created array in the same way.

Most of the time you'll find yourself using dynamic allocation in situations where static initialization doesn't really make sense anyway. Such as when you have arrays containing thousands of items. So this isn't usually a big deal.


Using helper variable:

const int p_data[] = {1, 2, 3};
int* p = (int*)memcpy(new int[3], p_data, sizeof(p_data));

or, one line

int p_data[] = {1, 2, 3},  *p = (int*)memcpy(new int[3], p_data, sizeof(p_data));


Never heard of such thing possible, that would be nice to have.

Keep in mind that by initializing the array in the code that way

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

..... only gains you easier code writing and NOT performance. After all, the CPU will do the work of assigning values to the array, either way you do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜