Initialize all elements of an array to same value in C/C++

  1. Using Designated Initializers
// or don't specify the size
int arr[] = {[0 ... 4] = 1};
  1. Using std::fill_n function
    Finally, we can use std::fill_n in C++, which assigns a value to the first n array elements.
#include <iostream>
#include <algorithm>
 
int main()
{
    int n = 5;
    int val = 1;
 
    int arr[n];
    std::fill_n (arr, n, val);
 
    // always prints 1
    std::cout << arr[rand() % n];
 
    return 0;
}
posted @ 2022-11-19 16:45  ChrainY  阅读(16)  评论(0编辑  收藏  举报