如何获得阶乘<a>....<b> 运行时阶乘?

How to get factorial<a>....factorial<b> at runtime?

本文关键字:gt 阶乘 lt 运行时 何获得      更新时间:2023-10-16

我想用编译时计算的整数填充查找表:

#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";
}

这对于少量元素很好,但是当查找表包含大量元素时,我该怎么办?如何在不显式写入每个元素的情况下填充数组?

factorial仅适用于示例。在更现实的情况下,我想在查找表中存储 ~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>{});
}

在此处查看一个完整的工作示例。

诀窍是std::make_integer_sequence<int, S>{}将创建一个std::integer_sequence<int, S...>的实例。因此,帮助程序函数get_lookup_table_impl能够推断其参数包。然后,factorial<S>::value...解压缩它并将每个S值传递给factorial。覆盖有大括号,可用于初始化任何类型的 std 容器。我用过std::array,但你可以使用任何你想要的东西。

可以在此处使用用于阵列初始化的参数包扩展:

#include <iostream>
#include <type_traits>
#include <utility>
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> {};
template<std::size_t... Is>
int get_factorial_impl(int x,std::index_sequence<Is...>)
{
if (x < 1) return -1;
if (x > 5) return -1;
static constexpr int lookup_table[] = { factorial<Is+1>::value...};
return lookup_table[x-1];
}
int get_factorial(int x)
{
return get_factorial_impl(x,std::make_index_sequence<5>{});
}
int main() {        
int x;
std::cin >> x;
std::cout << get_factorial(x) << "n";
}