有没有办法在 C++ 中静态初始化动态分配的数组? [英] Is there a way to statically-initialize a dynamically-allocated array in C++?
本文介绍了有没有办法在 C++ 中静态初始化动态分配的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C++ 中,我可以静态初始化一个数组,例如:
In C++, I can statically initialize an array, e.g.:
int a[] = { 1, 2, 3 };
是否有一种简单的方法可以将动态分配的数组初始化为一组立即数?
Is there an easy way to initialize 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?
推荐答案
你可以在 C++0x 中:
You can in C++0x:
int* p = new int[3] { 1, 2, 3 };
...
delete[] p;
但我更喜欢向量:
std::vector<int> v { 1, 2, 3 };
如果您没有 C++0x 编译器,boost 可以帮助您:
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);
这篇关于有没有办法在 C++ 中静态初始化动态分配的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文