Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a lookup table at compile time

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?

like image 840
Markus O Avatar asked May 19 '19 10:05

Markus O


People also ask

Are lookup tables faster?

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.

What is the main purpose of creating a lookup table?

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.


1 Answers

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);
like image 120
DeviatioN Avatar answered Sep 27 '22 17:09

DeviatioN