代码之家  ›  专栏  ›  技术社区  ›  enanone

初始化std::array的std::array

  •  4
  • enanone  · 技术社区  · 6 年前

    我有 std::array 属于 std::数组 ,并表示我想将所有数组初始化为 {1,2,3} 我们写道:

    std::array<std::array<int,3>,3> x{{1,2,3},{1,2,3},{1,2,3}};
    

    这不是很方便。如果有3个以上的数组,或者每个数组有3个以上的元素,就会变得非常混乱。

    然而,如果阵列的大小未知,情况会变得更糟 先验的 :

    template <size_t n, size_t T> struct foo{
      std::array<std::array<int,n>,T> x;
    }
    

    如何初始化 x ? 为了更清楚,我想初始化中的所有数组 十、 指向给定的某个参数的数组。也就是说,类似于:

    template <size_t n, size_t T> struct foo{
      static constexpr int N{20};
    
      std::array<std::array<int,n>,T> x;
    
      foo() : x{ {N,N,...}, {N,N,...}, ...} {}
    }
    

    (如果可能的话)。有什么建议或想法吗?我总是可以反复浏览 十、 调用方法和 fill ,如以下代码所示:

    for (size_t idx = 0; idx < x[0].size(); idx++)
      x[idx].fill(N);
    

    但这不是初始化,对吗?我不习惯使用 std::数组 我不知道我是不是在问一些愚蠢的问题:/

    1 回复  |  直到 6 年前
        1
  •  1
  •   Passer By    6 年前

    具有 std::index_sequence ,你可以这样做:

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

    然后:

    template <size_t n, size_t T>
    struct foo{
        static constexpr int N{20};
    
        std::array<std::array<int,n>,T> x;
    
        foo() : x{make_array<T>(make_array<n>(N))} {}
    };