在C ++中声明后的2D数组值分配 [英] 2D Array Value Assign After Declaration in C++

查看:70
本文介绍了在C ++中声明后的2D数组值分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在声明数组时要为2D数组赋值时,我们这样做:

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 ++中声明后的2D数组值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆