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

前端 未结 6 860
囚心锁ツ
囚心锁ツ 2020-12-03 17:40

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

6条回答
  •  余生分开走
    2020-12-03 18:07

    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 values = {T(1), T(2), T(3), T(4), T(5), T(6)};
    std::vector  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  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.

提交回复
热议问题