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

前端 未结 6 846
囚心锁ツ
囚心锁ツ 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 17:54

    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));
    
    0 讨论(0)
  • 2020-12-03 18:03

    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)

    0 讨论(0)
  • 2020-12-03 18:03

    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.

    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2020-12-03 18:15

    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);
    
    0 讨论(0)
  • 2020-12-03 18:16

    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 讨论(0)
提交回复
热议问题