如何获得阶乘<a>....<b> 运行时阶乘?
How to get factorial<a>....factorial<b> at runtime?
我想用编译时计算的整数填充查找表:
#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";
}
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 阶乘问题在 c++ 中给出错误的输出
- 大数的阶乘给出错误的输出
- 什么模板用法在阶乘中更好
- 为什么我在C++阶乘函数中出现编译错误?
- 计算阶乘的 C++17 倍表达式中的错误
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- 平方模型为零,阶乘模型问题
- 阶乘元规划
- 阶乘-c++ 我想以不同的方式打印
- 阶乘函数只返回C++中输入的答案
- 阶乘使用循环递增给出垃圾值
- 大 n 表示阶乘
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- 计算最大数字的阶乘
- 这个阶乘程序内部发生了什么?
- 返回阶乘C++的递归函数
- C++ 中是否有任何内置阶乘函数?
- 高效计算阶乘