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

后端 未结 16 2001
伪装坚强ぢ
伪装坚强ぢ 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:06

    Just use the fill_n() method.

    Example

    int n;
    cin>>n;
    int arr[n];
    int value = 9;
    fill_n(arr, n, value); // 9 9 9 9 9...
    

    Learn More about fill_n()

    or

    you can use the fill() method.

    Example

    int n;
    cin>>n;
    int arr[n];
    int value = 9;
    fill(arr, arr+n, value); // 9 9 9 9 9...
    

    Learn More about fill() method.

    Note: Both these methods are available in algorithm library (#include). Don't forget to include it.

提交回复
热议问题