gpt4 book ai didi

c++ - 如何从 initializer_list 初始化二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:43 25 4
gpt4 key购买 nike

typedef unsigned char u8;

template <u8 N>
class matrix {
public:
matrix(const std::initializer_list<std::initializer_list<int>>& l);
private:
std::array<std::array<int, N>, N> arr;
};

template <u8 N>
matrix<N>::matrix(const std::initializer_list<std::initializer_list<int>>& l) : arr(l) {}

error C2664: 'std::array,2>::array(std::array,2> &&)': cannot convert argument 1 from 'const std::initializer_list>' to 'const std::array,2> &'

如何从 2D std::initializer_list 初始化 2D std::array(或 C 数组)?

最佳答案

std::array 是一个集合。这意味着您可以从 braced-init-list 中初始化它

std::array<int, 4> foo = {1,2,3,4};

在您的构造函数中,虽然您没有braced-init-list,但您有一个std::initlizer_list,它不能用于初始化一个std::数组。您需要做的是将 std::initlizer_list 中的数据复制到数组中,例如

template <u8 N>
matrix<N>::matrix(std::initializer_list<std::initializer_list<int>> l)
{
u8 counter = 0;
for (auto row : l)
std::copy(row.begin(), row.end(), arr[counter++].begin());
}

另请注意,您不必传递 by std::initlizer_list 引用。它是一个轻量级对象,可以按值传递,不会复制底层元素。


您可以更改您的类以将二维数组作为参数,这样您就可以直接用它初始化 arr 但因为 how you have to initialize aggregates of aggregates你会陷入花括号 hell ,因为你的代码会变成

typedef unsigned char u8;

template <u8 N>
class matrix {
public:
matrix(std::array<std::array<int, N>, N> l);
private:
std::array<std::array<int, N>, N> arr;
};

template <u8 N>
matrix<N>::matrix(std::array<std::array<int, N>, N> l) : arr(l) {}


int main()
{
std::array<std::array<int, 2>, 2> arr{{{{1, 2}}, {{3, 4}}}}; // this is how you have to initialize a 2d std::array

matrix<2> m = {{{{{1, 2}}, {{3, 4}}}}}; // we need one more brace here since we are initialzing the matrix, which needs its own brace
}

关于c++ - 如何从 initializer_list 初始化二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52631355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com