我想用编译时计算的整数填充查找表:
#include <iostream>
#include <type_traits>
template <int x> using number = std::integral_constant<int,x>;
template <int n> struct factorial : number<n * factorial<n-1>::value> {};
template <> struct factorial<0> : number<1> {};
int get_factorial(int x) {
if (x < 1) return -1;
if (x > 5) return -1;
static constexpr int lookup_table[] = {
factorial<1>::value,
factorial<2>::value,
factorial<3>::value,
factorial<4>::value,
factorial<5>::value
};
return lookup_table[x-1];
}
int main() {
int x;
std::cin >> x;
std::cout << get_factorial(x) << "\n";
}
这对于少量元素来说没问题,但是当查找表包含大量元素时我该怎么办?如何在不显式写入每个元素的情况下填充数组?
阶乘
仅用于示例。在更现实的场景中,我想在查找表中存储 ~1000 个元素。
最佳答案
使用 C++14,您可以使用 std::integer_sequence
:
template <int... S>
constexpr std::array<int, sizeof...(S)> get_lookup_table_impl(std::integer_sequence<int, S...>)
{
return { factorial<S>::value... };
}
template <int S>
constexpr auto get_lookup_table()
{
return get_lookup_table_impl(std::make_integer_sequence<int, S>{});
}
查看完整的示例 here .
诀窍是 std::make_integer_sequence<int, S>{}
将创建 std::integer_sequence<int, S...>
的实例。所以,辅助函数get_lookup_table_impl
能够推导出它的参数包。然后,factorial<S>::value...
解压它并传递 S
的每个值至factorial
。用大括号覆盖,这可用于初始化任何类型的 std 容器。我用过std::array
,但您可以使用任何您想要的。
关于c++ - 如何在运行时获取阶乘<a>....阶乘<b>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543776/