Initialization of all elements of an array to one default value in C++?

前端 未结 13 1249
礼貌的吻别
礼貌的吻别 2020-11-22 07:59

C++ Notes: Array Initialization has a nice list over initialization of arrays. I have a

int array[100] = {-1};

expecting it to be full with

13条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:37

    Using the syntax that you used,

    int array[100] = {-1};
    

    says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

    In C++, to set them all to -1, you can use something like std::fill_n (from ):

    std::fill_n(array, 100, -1);
    

    In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

提交回复
热议问题