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

您好我正在学习C ++ 11,我想知道如何使constexpr 0到n数组,例如:


n = 5;


int array[] = {0 ... n};

所以数组可能是 {0, 1, 2, 3, 4, 5}


九州编程
浏览 418回答 3
3回答

慕容森

在C ++ 14中,可以使用constexpr构造函数和循环轻松完成:#include <iostream>template<int N>struct A {&nbsp; &nbsp; constexpr A() : arr() {&nbsp; &nbsp; &nbsp; &nbsp; for (auto i = 0; i != N; ++i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[i] = i;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; int arr[N];};int main() {&nbsp; &nbsp; constexpr auto a = A<4>();&nbsp; &nbsp; for (auto x : a.arr)&nbsp; &nbsp; &nbsp; &nbsp; std::cout << x << '\n';}

MMMHUHU

基于@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...>)&nbsp;-> std::array<typename std::result_of<Function(std::size_t)>::type, sizeof...(Indices)>&nbsp;{&nbsp; &nbsp; 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>&nbsp;{&nbsp; &nbsp; return make_array_helper(f, std::make_index_sequence<N>{});&nbsp; &nbsp;&nbsp;}constexpr double fun(double x) { return x * x; }int main()&nbsp;{&nbsp; &nbsp; constexpr auto N = 10;&nbsp; &nbsp; constexpr auto a = make_array<N>(fun);&nbsp; &nbsp; std::copy(std::begin(a), std::end(a), std::ostream_iterator<double>(std::cout, ", "));&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP