我希望创建一个坐标查找表,例如:
int a[n][2] = {{0,1},{2,3}, ... }
对于给定的 n
, 在编译时创建。我开始研究 constexpr
, 但似乎是一个返回 constexpr std::vector<std::array <int, 2> >
的函数据我所知,这不是一个选择:
invalid return type 'std::vector<std::array<int, 2ul> >' of constexpr function
怎样才能创建这样一个编译时数组?
最佳答案
使用 C++14,您不需要太多的模板魔法。这里是一个如何为 f(x) = x^3
查找表的示例,其中第一个坐标是 x
值,第二个坐标是 f(x)
值:
#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';
}
关于c++ - 使用 constexpr 查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016099/