2

Is there already a way where I can initialize an array directly in a struct? Like this:

struct S
{
  int arr[50] = {5};  
}

I know this only initializes the first element of the array, but is there any way to write something similar with g++ but that can initialize all elements of the array with 5?

I've read that with gcc we can use designated intializers int arr[50] = {[0 ... 49] = 5}; but this won't be possible in C++.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Upgrade
  • 95
  • 6

1 Answers1

2

Since a struct object needs to have its constructor called when being initialized you can just perform this assignment inside the constructor, e.g.:

struct S
{
  int arr[50];  
  S() {
    for (int& val : arr) val = 5;
  }
};

Or similarly you can use std::fill from the algorithm header

#include <algorithm>
struct S
{
  int arr[50];  
  S() {
    std::fill(std::begin(arr), std::end(arr), 5);
  }
};
UnholySheep
  • 3,967
  • 4
  • 19
  • 24
  • Yup - I believe [std::fill()](https://en.cppreference.com/w/cpp/algorithm/fill) is exactly what the OP looking for :) – paulsm4 Feb 13 '22 at 00:31