如何在声明后立即为新初始化的数组赋值

时间:2014-07-05 11:48:31

标签: c++ arrays initialization

如果我使用指针,如何给出新的初始化数组的值? E.g。

int* array = new int[3];  <- I want to give the values {1,2,3} on the same row but not:

array[0] = 5;
array[1] = 3;
array[2] = 4;

2 个答案:

答案 0 :(得分:5)

您可以使用括号括起初始值设定项:

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

通常的警告是,您需要确保在delete []上致电array。这比第一眼看到的更难保证。出于这个原因和其他原因,使用std::vector<int>

可能是个更好的主意
std::vector<int> v{1,2,3};

如果您遇到较旧的C ++ 11之前的实现,那么您就无法使用大括号括起来的初始化语法。您将不得不在某个级别使用循环(无论是您自己的循环,还是使用某些标准或第三方库函数。)

答案 1 :(得分:3)

如果你绝对必须使用C ++ 98,你可以这样做:

#include <algorithm>    //copy
#include <iostream>     // cout
#include <iterator>     // iostream_iterator

void foo()
{
    int init[] = { 1, 2, 3 };
    int* array = new int[3]; 
    std::copy(init, init + 3, array);
    std::copy(array, array + 3, std::ostream_iterator<int>(std::cout, ", "));

    // better hope nothing bad like an exception happens in between

    delete[] array;
}

int main() 
{    
    foo();
}

Live Example。因此,您定义了一个初始化器的C数组,并将它们复制到动态分配的数组中。退出init时,系统会自动删除C阵列foo(),但您必须手动删除array。建议的方法是在C ++ 11中使用带有初始化列表的std::vector