在编译时使用数学公式填充std :: array

Jua*_*nto 3 c++ arrays compile-time fill constexpr

我想使用数学函数在编译时填充constexpr std :: array。有可能以简单的方式吗?

我找到了以下解决方案:C ++ 11:数组的编译时间计算。但是,还有其他仅使用std的现代解决方案吗?这似乎让我感到困惑。

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];
   // ...
}


Run Code Online (Sandbox Code Playgroud)

L. *_* F. 6

这是一种不混淆的方法:将计算结果包装在一个函数中:

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;
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

constexpr std::array<double, 10000> arr = generate<10000>();
Run Code Online (Sandbox Code Playgroud)

现场演示

之所以可行,是因为自C ++ 14起,constexpr函数中允许使用循环,并且只要变量的生命周期在常量表达式的求值内开始,就可以对其进行修改。