How to initialize all elements in an array to the same number in C++

后端 未结 16 1947
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 07:17

I\'m trying to initialize an int array with everything set at -1.

I tried the following, but it doesn\'t work. It only sets the first value at -1.

in         


        
16条回答
  •  [愿得一人]
    2020-12-05 08:00

    The reason that int directory[100] = {-1} doesn't work is because of what happens with array initialization.

    All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.

    ints which are implicitly initialized are:

    initialized to unsigned zero

    All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration.

    C++11 introduced begin and end which are specialized for arrays!

    This means that given an array (not just a pointer), like your directory you can use fill as has been suggested in several answers:

    fill(begin(directory), end(directory), -1)
    

    Let's say that you write code like this, but then decide to reuse the functionality after having forgotten how you implemented it, but you decided to change the size of directory to 60. If you'd written code using begin and end then you're done.
    If on the other hand you'd done this: fill(directory, directory + 100, -1) then you'd better remember to change that 100 to a 60 as well or you'll get undefined behavior.

提交回复
热议问题