Jab*_*cky 23 c++ initialization stdarray
我需要std::array使用常量值初始化a的所有元素,就像可以使用来完成一样std::vector。
#include <vector>
#include <array>
int main()
{
std::vector<int> v(10, 7); // OK
std::array<int, 10> a(7); // does not compile, pretty frustrating
}
Run Code Online (Sandbox Code Playgroud)
有没有办法优雅地做到这一点?
现在我正在使用这个:
std::array<int, 10> a;
for (auto & v : a)
v = 7;
Run Code Online (Sandbox Code Playgroud)
但我想避免使用显式代码进行初始化。
Jar*_*d42 20
使用std::index_sequence,您可以执行以下操作:
namespace detail
{
template <typename T, std::size_t ... Is>
constexpr std::array<T, sizeof...(Is)>
create_array(T value, std::index_sequence<Is...>)
{
// cast Is to void to remove the warning: unused value
return {{(static_cast<void>(Is), value)...}};
}
}
template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
return detail::create_array(value, std::make_index_sequence<N>());
}
Run Code Online (Sandbox Code Playgroud)
随着使用
auto a = create_array<10 /*, int*/>(7); // auto is std::array<int, 10>
Run Code Online (Sandbox Code Playgroud)
与std::fill解决方案相反,它处理非默认构造类型。
Bat*_*eba 19
las std::array支持聚合初始化,但这还不够。
幸运的是可以使用std::fill,或甚至std::array<T,N>::fill,其中,从C ++ 20 是优雅因为后者变得constexpr。
参考:https://en.cppreference.com/w/cpp/container/array/fill
h4c*_*net 12
您可以执行以下操作
std::array<int, 10> a;
a.fill(2/*or any other value*/);
Run Code Online (Sandbox Code Playgroud)
或std::fill从算法头文件使用。包括算法头文件使用
#include <algorithm>
Run Code Online (Sandbox Code Playgroud)
从 C++17 开始,您可以编写一个 constexpr 函数来有效地设置数组,因为元素访问器现在是 constexpr。此方法也适用于设置初始值的各种其他方案:
#include <array>
template<typename T, size_t N>
constexpr auto make_array(T value) -> std::array<T, N>
{
std::array<T, N> a{};
for (auto& x : a)
x = value;
return a;
}
int main()
{
auto arr = make_array<int, 10>(7);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |