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.
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} };
}
or using std::array
:
#include <array>
int main()
{
std::array<std::array<int,4>,2> arr ;
arr = {{ {{1,2,3,4 }}, {{5,6,7,8}} }} ;
}
Note, the double set of braces in both the inner and outer set. This answer though only works in C++11.
来源:https://stackoverflow.com/questions/16059781/2d-array-value-assign-after-declaration-in-c