2D Array Value Assign After Declaration in C++

蹲街弑〆低调 提交于 2019-12-08 07:06:56

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!