问题描述
如何使用一维数组列表初始化二维数组?
How can I initialize 2d array with a list of 1d arrays?
void main()
{
int a[] = { 1,2,3 };
int b[] = { 4,5,6 };
int array[][3] = { a,b };
}
推荐答案
C ++中的原始数组属于第二类公民.无法分配它们,也不能复制它们,这意味着您不能使用它们来初始化其他数组,并且它们的名称在大多数情况下会变成指针.
raw arrays in C++ are kind of second class citizens. They can't be assigned and they can't be copied, which means you can't use them to initialize other arrays, and their name decays into a pointer in most circumstances.
Lucky C ++ 11提供了一种解决方案. std::array
的作用类似于原始数组,但是没有缺点.您可以改用它们来构建二维数组,例如
Lucky C++11 offers a solution. std::array
acts like a raw array, but it doesn't have the drawbacks. You can use those instead to build a 2d array like
std::array<int, 3> foo = {1,2,3};
std::array<int, 3> bar = {3,4,5};
std::array<std::array<int, 3>, 2> baz = {foo, bar};
并且如果您具有C ++ 17支持,则可以利用类模板参数推导摆脱了必须指定模板参数的麻烦,并且代码简化为
and if you have C++17 support you can leverage class template argument deduction to get rid of having to specify the template parameters and the code simplifies to
std::array foo = {1,2,3};
std::array bar = {3,4,5};
std::array baz = {foo, bar};
您可以在此在线示例中找到工作
which you can see working in this live example
这篇关于如何使用一维数组列表初始化二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!