第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在C ++ 11中創(chuàng)建N元素constexpr數(shù)組

在C ++ 11中創(chuàng)建N元素constexpr數(shù)組

C++
九州編程 2019-12-12 14:10:48
您好我正在學習C ++ 11,我想知道如何使constexpr 0到n數(shù)組,例如:n = 5;int array[] = {0 ... n};所以數(shù)組可能是 {0, 1, 2, 3, 4, 5}
查看完整描述

3 回答

?
慕容森

TA貢獻1853條經(jīng)驗 獲得超18個贊

在C ++ 14中,可以使用constexpr構(gòu)造函數(shù)和循環(huán)輕松完成:


#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條經(jīng)驗 獲得超8個贊

基于@Xeo的出色創(chuàng)意,這是一種讓您填寫一系列


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

在哪里T是任何文字類型(不只是int或其他有效的非類型模板參數(shù)類型),而且還是double,或std::complex(從C ++ 14開始)

fun()任何constexpr功能在哪里

std::make_integer_sequence從C ++ 14開始支持該功能,但今天可以輕松地用g ++和Clang來實現(xiàn)(請參見答案末尾的實時示例)

我在GitHub上使用@JonathanWakely的實現(xiàn)(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 關(guān)注
  • 450 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號