C++ 为什么 std::array 没有一个构造函数来为要填充的数组取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17923683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:33:42  来源:igfitidea点击:

Why does std::array not have an constructor that takes a value for the array to be filled with?

c++c++11stdarray

提问by rubenvb

Is the absence of

是否缺席

std::array<T,size>::array(const T& value);

an oversight? It seems mighty useful to me, and dynamic containers (like std::vector) do have a similar constructor.

疏忽?这对我来说似乎很有用,动态容器(如std::vector)确实有一个类似的构造函数。

I am fully aware of

我完全知道

std::array<T,size>::fill(const T& value);

but that is not a constructor, and the memory will be zeroed out first. What if I want all -1's like this guy?

但这不是构造函数,内存将首先清零。如果我想所有-1的喜欢这个家伙

采纳答案by Mike Seymour

std::arrayis, by design, an aggregate, so has no user-declared constructors.

std::array是,按照设计,聚合,所以没有用户声明的构造函数。

As you say, you could use fillafter default constructing. Since it's an aggregate, default construction won't zero the memory, but will leave it uninitialised (if the contained type is trivially initialisable).

正如您所说,您可以fill在默认构造之后使用。由于它是一个聚合,默认构造不会将内存归零,但会使其未初始化(如果包含的类型可以简单初始化)。

回答by tohava

Note that you can efficiently simulate this type of constructor by taking advantage of the fact that array is not zero-initialized, and has a copy constructor and do.

请注意,您可以利用数组不是零初始化的事实来有效地模拟这种类型的构造函数,并且具有复制构造函数和 do。

template <size_t N, class T>
array<T,N> make_array(const T &v) {
    array<T,N> ret;
    ret.fill(v);
    return ret;
}

auto a = make_array<20>('z');

回答by Jarod42

You may use std::index sequencefor that:

您可以std::index sequence为此使用:

namespace detail
{

    template <typename T, std::size_t...Is>
    constexpr std::array<T, sizeof...(Is)>
    make_array(const T& value, std::index_sequence<Is...>)
    {
        return {{(static_cast<void>(Is), value)...}};
    }
}

template <std::size_t N, typename T>
constexpr std::array<T, N> make_array(const T& value)
{
    return detail::make_array(value, std::make_index_sequence<N>());
}

Demo

演示

std::make_index_sequenceis C++14, but can be implemented in C++11.

std::make_index_sequence是 C++14,但可以在 C++11 中实现。

static_cast<void>(Is)is to handle evil operator,that Tmight provide.

static_cast<void>(Is)是柄邪operator,T可能会提供。

回答by Nawaz

First of all, it is not std::array<T>, it is std::array<T,N>where Nis compile time constant integral expression.

首先,它不是std::array<T>,它是std::array<T,N>这里N的编译时间常数积分表达式。

Second, std::arrayis made aggregate by design. So it doesn't have anything which makes it non-aggregate, which is why it doesn't have constructor... and destructor, virtual functions, etc.

第二,std::array通过设计聚合。所以它没有任何使它成为非聚合的东西,这就是为什么它没有构造函数......和析构函数、虚函数等。