用常量值初始化 std::array

新手上路,请多包涵

我需要用一个常数值初始化 std::array 的所有元素,就像它可以用 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
}

有没有办法优雅地做到这一点?

现在我正在使用这个:

 std::array<int, 10> a;
for (auto & v : a)
  v = 7;

但我想避免使用显式代码进行初始化。

原文由 Jabberwocky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 651
2 个回答

使用 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>());
}

随着使用

auto a = create_array<10 /*, int*/>(7); // auto is std::array<int, 10>

其中,与 std::fill 解决方案相反,处理非默认可构造类型。

原文由 Jarod42 发布,翻译遵循 CC BY-SA 4.0 许可协议

唉,不是; std::array 支持 _聚合初始化_,但这还不够。

幸运的是,您可以使用 std::fill ,甚至 std::array<T,N>::fill ,从 C++20 开始,它 优雅的,因为后者变为 constexpr

参考: https ://en.cppreference.com/w/cpp/container/array/fill

原文由 Bathsheba 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题