0

I'd like to create an array in compile-time. The problem is, that it's gonna be huge(int arr[8000000]), so recursion with variadics or Nested Structures ain't gonna work. Global array has to be initialised while created, and it isn't jus a simple fill {0}. Does anyone have any idea how-to? For the matter of this post, lets say i want to have arr[i]=i.

Farkor123
  • 39
  • 4
  • Write a script that will generate your array as a header file and include it elsewhere? – freakish Oct 11 '18 at 09:07
  • I suspect put **8000000** int on static memory is not good idea. Maybe load from file? – apple apple Oct 11 '18 at 09:10
  • @Zinki for 8000000 elements it cant be initialised in brackets, and recursion-depth is a blocker for variadics – Farkor123 Oct 11 '18 at 09:10
  • @freakish i need it to be in one file, i'll add that to the post – Farkor123 Oct 11 '18 at 09:10
  • 1
    @Farkor123 That's a weird requirement. What C++ version are we talking about? `constexpr` looping in C++14 is a valid option as well. – freakish Oct 11 '18 at 09:11
  • @appleapple i have lots memory but tiny time limits – Farkor123 Oct 11 '18 at 09:11
  • @freakish You misunderstood. I need it to be just one-filer, and the testing machine for my code will have lots of memory, but each test needs to be at worst 1s long, but compile-time is not included. What do you mean by constexpr looping? – Farkor123 Oct 11 '18 at 09:13
  • @Farkor123 Ok, but I still don't understand why "one file" is a necessary requirement? You surely don't write entire code in a single file, do you? – freakish Oct 11 '18 at 09:15
  • @Farkor123 Have a look at the third answer in the link posted by Zinki. – freakish Oct 11 '18 at 09:16
  • @Farkor123 there are multiple answers in the linked thread, at least one of which appears to satisfy your requirements (no recursion, no nested structures). – Zinki Oct 11 '18 at 09:18

1 Answers1

1

You might use constexpr function, something like:

constexpr auto make_huge_array()
{
    std::array<int, 8'000'000> res{};

    std::size_t i = 0;
    for (auto& e : res) {
         e = i++;
    }
    return res;
}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302