C++ noob here. What's the simplest way to create the array {f(0), f(1), ..., f(1023)}
at compile time, given a constexpr f
?
Because table lookups and simple estimations can be faster than mathematical function evaluations, using lookup table blocks often result in speed gains when simulating a model.
In data analysis applications, such as image processing, a lookup table (LUT) is used to transform the input data into a more desirable output format. For example, a grayscale picture of the planet Saturn will be transformed into a color image to emphasize the differences in its rings.
You can use an immediately invoked lambda:
#include <array>
using ResultT = int;
constexpr ResultT f(int i)
{
return i * 2;
}
constexpr auto LUT = []
{
constexpr auto LUT_Size = 1024;
std::array<ResultT, LUT_Size> arr = {};
for (int i = 0; i < LUT_Size; ++i)
{
arr[i] = f(i);
}
return arr;
}();
static_assert(LUT[100] == 200);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With