Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookup table with constexpr

I'm looking to create a lookup table of coordinates, something like:

int a[n][2] = {{0,1},{2,3}, ... }

For a given n, to be created at compile time. I started looking into constexpr, but is seems like a function returning a constexpr std::vector<std::array <int, 2> > isn't an option, as I get:

invalid return type 'std::vector<std::array<int, 2ul> >' of constexpr function

How can create such a compile time array?

like image 970
nbubis Avatar asked Sep 25 '13 22:09

nbubis


People also ask

What is a lookup table C++?

A "lookup table" is simply a container (any kind of container) that contains values you look up, and usually map to some other value. In its simplest form, consider the following: struct MapIntToString { int value; char* string; }; MapIntToString my_map[] = { { 1, "one" }, { 2, "two" }, { 3, "three" }, // ... };

What is constexpr in C ++ 11?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.

Can a function return constexpr?

A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type.

Does constexpr improve performance?

Understanding constexpr Specifier in C++ constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time.


1 Answers

With C++14, you do not need too much template magic. Here an example of how to have a lookup table for f(x) = x^3 with the first coordinate being the x value and the second coordinate being the f(x) value:

#include <iostream>

template<int N>
struct Table
{
    constexpr Table() : values()
    {
        for (auto i = 0; i < N; ++i)
        {
            values[i][0] = i;
            values[i][1] = i * i * i;
        }
    }
    int values[N][2];
};

int main() {
    constexpr auto a = Table<1000>();
    for (auto x : a.values)
        std::cout << "f(" << x[0] << ") = " << x[1] << '\n';
}
like image 83
IceFire Avatar answered Sep 30 '22 19:09

IceFire