我想在编译时使用数学函数填充一个 constexpr std::array。是否可以通过简单的方式实现?
我找到了这个解决方案:C++11: Compile Time Calculation of Array .但是,还有其他仅使用 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];
// ...
}
最佳答案
这是一个不会混淆的方法:将计算包装在一个函数中:
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;
}
使用示例:
constexpr std::array<double, 10000> arr = generate<10000>();
( live demo )
这是可行的,因为自 C++14 起,constexpr 函数中允许循环,并且只要变量的生命周期从常量表达式的求值开始,就可以修改变量。
关于c++ - 在编译时使用数学公式填充 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721388/