2012-07-07 142 views
0

Possible Duplicate:
How do I use arrays in C++? (FAQ)
Using dynamic multi-dimensional arrays in c++動態分配一個二維數組

void fillTestCase (int * tC) 
{ 
    ifstream infile; 
    infile.open("input00.txt",ifstream::in); 
    int * tempGrid; 
    int i,j; 
    infile >>i; 
    infile >>j; 
    tempGrid = new int[i][j]; 
} 

給我一個錯誤:

error C2540: non-constant expression as array bound 
error C2440: '=' : cannot convert from 'int (*)[1]' to 'int *' 

我怎樣才能使這個兩個維動陣列的動態?

+1

首先相關的問題:http://stackoverflow.com/questions/1471721/using-dynamic-multi-dimensional-arrays-in-c?rq = 1 – chris 2012-07-07 20:08:13

+2

只是拋出它:如果可以的話,請使用'std :: vector'。 – chris 2012-07-07 20:14:57

+1

SO的C++ FAQ條目___ [如何在C++中使用數組?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c)___有幾個段落在多維數組上。 – sbi 2012-07-07 20:18:18

回答

1

最簡單的方法是將數組設置爲一維,並自己計算索引。

僞代碼:

int MaxWidth; 
int MaxHeight; 
int* Array; 

Array=new int[MaxWidth*MaxHeight]; 

int Column, Row; 
... 

Element=Array[Row*MaxWidth+Column]; 
+2

我認爲你應該添加爲什麼他的代碼不起作用。 – 2012-07-07 20:14:41

1

到目前爲止,最好的方法是使用boost multidimensional array library

它們用於3 d陣列例如:

int main() 
{ 
    // Create a 3D array 
    typedef boost::multi_array<double, 3> array_type; 
    typedef array_type::index index; 

    for (int x = 3; x < 5; ++x) 
    { 
     int y = 4, z = 2; 

     array_type A(boost::extents[x][y][z]); 

     // Assign values to the elements 
     int values = 0; 
     for(index i = 0; i != x; ++i) 
     for(index j = 0; j != y; ++j) 
      for(index k = 0; k != z; ++k) 
      A[i][j][k] = values++; 

     // Verify values 
     int verify = 0; 
     for(index i = 0; i != x; ++i) 
     for(index j = 0; j != y; ++j) 
      for(index k = 0; k != z; ++k) 
      assert(A[i][j][k] == verify++); 
    } 

    return 0; 
}