2013-04-17 52 views
1

我知道当我们想要的值,我们宣布的阵列分配到二维数组,我们这样做:二维数组赋值++宣言℃之后

int myArray[2][4] = {{1,2,3,4},{5,6,7,8}}; 

但是我应该如何宣称它“后”赋值?我想要做这样的事情:

int myArray[2][4]; 

myArray = {{1,2,3,4},{5,6,7,8}}; 

当我这样做,编译器为错误。请帮助。

+0

请参阅http://stackoverflow.com/questions/8886375/possible-to-initialize-an-array-after-the-declaration-in-c – zakinster

+3

平面数组不可分配,所以您必须填写每个元素个别。你可以考虑使用一个标准的库容器,比如'std :: array'。 – juanchopanza

+1

您可以使用C++ 11和'std :: vector'吗? –

回答

2

如果你想使用std::vector那么你可以这样做:

#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。

+0

我可以像arrV [1] [2]一样使用它以后分配值吗? –

+0

@MohammadRezaHajianpour是的,这是正确的。 –