Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an std::array using math formula in compile time

I want to fill a constexpr std::array in compile time using a math function. Is it possible in an easy way?

I found this solution: C++11: Compile Time Calculation of Array. However, is there any other modern solution using only std? This one seems too confusing for me.

int main()
{
   // This is the array I need to fill
   constexpr std::array<double, 100000> elements;
   for (int i=0; i!=100000; ++i)
   {
      // Each element is calculated using its position with long exponential maths.
      elements[i] = complexFormula(i); // complexFormula is constexpr
   }


   double anyVal = elements[43621];
   // ...
}


like image 312
Juan JuezSarmiento Avatar asked Jan 28 '26 19:01

Juan JuezSarmiento


1 Answers

Here's a non-confusing approach: wrap the calculation in a function:

template <int N>
constexpr std::array<double, N> generate()
{
    std::array<double, N> arr{};
    for (int i = 0; i < N; ++i)
        arr[i] = complexFormula(i);
    return arr;
}

Usage example:

constexpr std::array<double, 10000> arr = generate<10000>();

(live demo)

This works because, since C++14, loops are allowed in a constexpr function, and variables can be modified as long as their lifetime starts within the evaluation of the constant expression.

like image 56
L. F. Avatar answered Jan 31 '26 11:01

L. F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!