【问题标题】:How can I initialise a constexpr array with values using std::generate如何使用 std::generate 初始化具有值的 constexpr 数组
【发布时间】:2021-06-08 20:58:17
【问题描述】:

例如,如果我想要一个 constexpr std::array<int,100> 在编译时初始化为 1-300 的所有 3 的倍数,我该怎么做?

我的第一个想法是使用 std::generate,类似于:

constexpr std::array<int,100> a { std::generate(a.begin(), a.end(), [n=0]()mutable{ return n+=3; });

我收到一个错误,例如&lt;source&gt;:9:52: error: void value not ignored as it ought to be

在这之后我不能使用 std::generate 因为当然,它在那个时候是只读的

感谢您的帮助

【问题讨论】:

标签: c++ constexpr constexpr-function


【解决方案1】:

你可以使用index_sequence:

template <size_t ... Indices>
constexpr auto gen(std::index_sequence<Indices...>) {
    return std::array<int,100>{ (Indices * 3)... };
}

int main() {
    constexpr std::array<int,100> a = gen(std::make_index_sequence<100>());
}

【讨论】:

  • 哇。折叠表达式的力量!
  • 折叠表达式的语法有点不同。上面是正常的解包参数pack,每个pack的值乘以3。
  • 哦,我还以为“折叠”也指这个。在这种情况下,...的力量!
【解决方案2】:

诀窍是将代码放入立即调用的 lambda 中。那么使用std::generate 还是普通循环都没关系:

constexpr std::array<int,100> a = []{
    std::array<int,100> ret{};
    std::generate(ret.begin(), ret.end(),  [n=0]() mutable {return n += 3;});
    return ret;
}();
constexpr std::array<int,100> a = []{
    constexpr std::array<int,100> ret{};
    for (std::size_t i = 0; i < ret.size(); i++)
        ret[i] = 3 * (1+i);
    return ret;
}();

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多