为了账号安全,请及时绑定邮箱和手机立即绑定

在C ++ 11中创建N元素constexpr数组

在C ++ 11中创建N元素constexpr数组

C++
九州编程 2019-12-12 14:10:48
您好我正在学习C ++ 11,我想知道如何使constexpr 0到n数组,例如:n = 5;int array[] = {0 ... n};所以数组可能是 {0, 1, 2, 3, 4, 5}
查看完整描述

3 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

在C ++ 14中,可以使用constexpr构造函数和循环轻松完成:


#include <iostream>


template<int N>

struct A {

    constexpr A() : arr() {

        for (auto i = 0; i != N; ++i)

            arr[i] = i; 

    }

    int arr[N];

};


int main() {

    constexpr auto a = A<4>();

    for (auto x : a.arr)

        std::cout << x << '\n';

}



查看完整回答
反对 回复 2019-12-13
?
MMMHUHU

TA贡献1834条经验 获得超8个赞

基于@Xeo的出色创意,这是一种让您填写一系列


constexpr std::array<T, N> a = { fun(0), fun(1), ..., fun(N-1) };

在哪里T是任何文字类型(不只是int或其他有效的非类型模板参数类型),而且还是double,或std::complex(从C ++ 14开始)

fun()任何constexpr功能在哪里

std::make_integer_sequence从C ++ 14开始支持该功能,但今天可以轻松地用g ++和Clang来实现(请参见答案末尾的实时示例)

我在GitHub上使用@JonathanWakely的实现(Boost许可)

这是代码


template<class Function, std::size_t... Indices>

constexpr auto make_array_helper(Function f, std::index_sequence<Indices...>) 

-> std::array<typename std::result_of<Function(std::size_t)>::type, sizeof...(Indices)> 

{

    return {{ f(Indices)... }};

}


template<int N, class Function>

constexpr auto make_array(Function f)

-> std::array<typename std::result_of<Function(std::size_t)>::type, N> 

{

    return make_array_helper(f, std::make_index_sequence<N>{});    

}


constexpr double fun(double x) { return x * x; }


int main() 

{

    constexpr auto N = 10;

    constexpr auto a = make_array<N>(fun);


    std::copy(std::begin(a), std::end(a), std::ostream_iterator<double>(std::cout, ", ")); 

}



查看完整回答
反对 回复 2019-12-13
  • 3 回答
  • 0 关注
  • 386 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信