使用非零值初始化 C 风格数组,无需循环

pac*_*der 5 c++ arrays

我们知道 C++ 允许用零初始化 C 风格的数组

int a[5] = {0};
// or
int a[5] = {};
Run Code Online (Sandbox Code Playgroud)

对于 std::array 也同样有效

std::array a<int, 5> = {};
Run Code Online (Sandbox Code Playgroud)

但是,这行不通:

int a[5] = {33}; // in memory( 33, 0, 0, 0, 0 )
std::array<int, 5> = {33}; // in memory( 33, 0, 0, 0, 0 )
Run Code Online (Sandbox Code Playgroud)

vector有没有办法在不使用or 的情况下用非零值初始化整个数组algorhtm

也许constexpr可以帮忙?最好的解决方案是什么?

附:

GCC 提供了这种语法

int a[5] = {[0 ... 4] = 33};
Run Code Online (Sandbox Code Playgroud)

但我不确定它对于其他编译器是否有效。

Bar*_*rry 6

你有什么反对的<algorithm>?我认为这很干净:

int a[5];                                  // not initialized here yet
std::fill(std::begin(a), std::end(a), 33); // everything initialized to 33
Run Code Online (Sandbox Code Playgroud)


小智 3

我有一些代码来实现std::array使用模板元编程的编译时初始化(当然)。

namespace impl {

    template <class SeqTy, size_t N, SeqTy FillVal, SeqTy... Seq>
    struct make_fill {
        using type = typename make_fill<SeqTy, N-1, FillVal, FillVal, Seq...>::type;
    };

    template <class SeqTy, SeqTy FillVal, SeqTy... Seq>
    struct make_fill<SeqTy, 0, FillVal, Seq...> {
        using type = std::integer_sequence<SeqTy, Seq...>;
    };

    template <class T>
    struct make_array;

    template <class SeqTy, SeqTy... Seq>
    struct make_array<std::integer_sequence<SeqTy, Seq...>> {
        static constexpr std::array<SeqTy, sizeof...(Seq)> value() { 
            return std::array<SeqTy, sizeof...(Seq)>{ {Seq...} };
        }
    };

} // end impl namespace

template <class SeqTy, size_t N, SeqTy FillVal = 0ul>
constexpr std::array<SeqTy, N> fill() {
    return impl::make_array<typename impl::make_fill<SeqTy, N, FillVal>::type>::value();
};
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用:

std::array<size_t, N> ones = fill<size_t,N,1ul>();
Run Code Online (Sandbox Code Playgroud)

我想如果你不想使用的话你可以很容易地适应它std::array