gpt4 book ai didi

c++ - 初始化数组的数组 - 问题

转载 作者:可可西里 更新时间:2023-11-01 17:41:49 28 4
gpt4 key购买 nike

好的,我知道在 C++ 中,可以这样初始化一个 - 比方说二维 - 数组:

int theArray[5][3] = { 
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15}
};

现在,如果我想使用预先存在的数组作为 theArray 的元素怎么办?

例如

// A, B, C, D,... have already been declared as :
// `const U64 A[] = { 1,2,3,4 };` etc...

const U64 multiDimArray[12][64] = {
A, B, C, D, E, F,
G, H, I, J, K, L
};

这个,尽管抛出一个错误:

cannot initialize an array element of type 'const U64' 
(aka 'const unsigned long long') with an lvalue of type 'const U64 [64]'

我明白了,但希望你能明白我的意思。

有没有一种解决方法可以让我轻松实现同样的目标? (任何建议 - 也许是使用 Boost 的东西? - 欢迎)

最佳答案

如果你使用 C++11,array 的初始化列表灵活:

std::array< array<U64, 64>, 12> multiDimArray = {
A, B, C, D, E, F,
G, H, I, J, K, L
};

将正常工作,假设 A..Lstd::array<64, U64> .

该数组确实没有开销 c 风格的数组。 Click here for official reference.

"The size and efficiency of array for some number of elements is equivalent to size and efficiency of the corresponding C-style array T[N]." (From the reference)


我说的是“灵活”,因为您可以像这样使用混合初始化列表:

std::array<int, 3> first_row = {1,2,3};
std::array<array<int, 3>, 2> a={
first_row,
{2, 2, 2}
};

您可以将其用作固定大小的数组,使用相同的操作:

a[1][2]=2; a[0][1]=1; a[0][2]=3;

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

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