在 C++ 中声明后的二维数组值分配 [英] 2D Array Value Assign After Declaration in C++
本文介绍了在 C++ 中声明后的二维数组值分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道当我们想在声明数组时为二维数组赋值时,我们这样做:
I know when we want to assign values to 2D arrays as we declare the array, we do this:
int myArray[2][4] = {{1,2,3,4},{5,6,7,8}};
但是我应该如何在"声明之后分配值?我想做这样的事情:
But how should I assign values "after" declaring it? I want to do something like this:
int myArray[2][4];
myArray = {{1,2,3,4},{5,6,7,8}};
当我这样做时,编译器给出错误.请帮忙.
When I do it, the compiler gives error. Help please.
推荐答案
如果你想使用 std::vector
那么你可以这样做:
If you want to use std::vector
then you can do this:
#include <vector>
int main()
{
std::vector< std::vector<int> > arrV ;
arrV = { {1,2,3,4}, {5,6,7,8} };
}
或使用 std::array
:
#include <array>
int main()
{
std::array<std::array<int,4>,2> arr ;
arr = {{ {{1,2,3,4 }}, {{5,6,7,8}} }} ;
}
注意,内套和外套中的双套大括号.这个答案虽然只适用于 C++11.
Note, the double set of braces in both the inner and outer set. This answer though only works in C++11.
这篇关于在 C++ 中声明后的二维数组值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文