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?
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" }, // ... };
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.
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.
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.
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';
}
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