Initializer list for dynamic arrays?

后端 未结 5 1625
一个人的身影
一个人的身影 2020-11-30 14:44

It is possible to give an initializer list to the definition of a static array. Example:

int main()
{
  int int_static[2] = {1,2};
}

Is a s

5条回答
  •  广开言路
    2020-11-30 15:40

    No, you will have to create the elements dynamically.

    Alternatively, you can use a local array and copy its elements over those of the dynamically allocated array:

    int main() {
       int _detail[] = { 1, 2 };
       int * ptr = new int[2];
       std::copy( _detail, _detail+(sizeof detail / sizeof *detail), ptr );
       delete [] ptr;
    }
    

    In the limited version of setting all elements to 0, you can use an extra pair of parenthesis in the new call:

    int * ptr = new int[2]();  // will value initialize all elements
    

    But you seem to be looking for a different thing.

提交回复
热议问题