首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在运行时获取factorial<a>....factorial<b>?

如何在运行时获取factorial<a>....factorial<b>?
EN

Stack Overflow用户
提问于 2019-04-06 05:49:03
回答 2查看 84关注 0票数 2

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

代码语言:javascript
复制
#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个元素。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-06 06:04:07

在C++14中,您可以使用std::integer_sequence

代码语言:javascript
复制
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,但是你可以使用任何你想要的东西。

票数 3
EN

Stack Overflow用户

发布于 2019-04-06 06:06:03

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

代码语言:javascript
复制
#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";
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55543776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档