简体   繁体   English

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

[英]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?我想在编译时使用数学 function 填充一个 constexpr std::array。是否有可能以简单的方式进行?

I found this solution: C++11: Compile Time Calculation of Array .我找到了这个解决方案: C++11: Compile Time Calculation of Array However, is there any other modern solution using only std?但是,还有其他仅使用 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];
   // ...
}


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. 这是有效的,因为从C ++ 14开始,constexpr函数中允许循环,并且只要它们的生命周期在常量表达式的计算中开始,就可以修改变量。

In c++14 you also have the possibility of using std::index_sequence for your purpose:在 c++14 中,您还可以使用std::index_sequence来达到您的目的:

template <std::size_t... I>
constexpr std::array<double, sizeof...(I)> generate_impl(std::index_sequence<I..>) noexcept
{
   return { complexFormula(I)... };
}

template <std::size_t N>
constexpr std::array<double, N> generate() noexcept
{
   return generate_impl(std::make_index_sequence<N>{});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM