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

后端 未结 16 2003
伪装坚强ぢ
伪装坚强ぢ 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 07:56

    I'm surprised at all the answers suggesting vector. They aren't even the same thing!

    Use std::fill, from :

    int directory[100];
    std::fill(directory, directory + 100, -1);
    

    Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:

    template 
    T* end(T (&pX)[N])
    {
        return pX + N;
    }
    

    Giving:

    int directory[100];
    std::fill(directory, end(directory), -1);
    

    So you don't need to list the size twice.

提交回复
热议问题