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
Why does std::array not have an constructor that takes a value for the array to be filled with?
提问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::array
is, by design, an aggregate, so has no user-declared constructors.
std::array
是,按照设计,聚合,所以没有用户声明的构造函数。
As you say, you could use fill
after 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 sequence
for 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>());
}
std::make_index_sequence
is 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 T
might 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 N
is compile time constant integral expression.
首先,它不是std::array<T>
,它是std::array<T,N>
这里N
的编译时间常数积分表达式。
Second, std::array
is 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
通过设计聚合。所以它没有任何使它成为非聚合的东西,这就是为什么它没有构造函数......和析构函数、虚函数等。