2014-10-28 21 views
1

將二維矩陣表示爲數組數組還是將一維數組轉換爲相應數組索引的函數的一維數組更快?如何在C++中表示二維矩陣

+2

基準,並找出。 – 2014-10-28 12:10:01

+0

我認爲這回答你的問題http://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster – WalkingRandomly 2014-10-28 12:12:17

+0

如果數組是動態分配的,可能是後者。 – 2014-10-28 12:13:28

回答

0

2D陣列是更方便,例如

const int rows = 100; 
const int cols = 100; 
int arr[rows][cols]; 

你指的數組元素作爲arr[i][j]其中0 <= i < rows0 <= j < cols

+1

更加方便,直到實際需要在運行時選擇的尺寸爲止。然後它會下降。 – 2014-10-28 12:27:15

3

你可以使一維陣列和行指針的陣列。然後,您將獲得兩全其美的優勢:一個具有良好內存位置和可預測訪問的方便界面。

int * matrix1d = new int [rows * cols]; 
int ** matrix2d = new int * [rows]; 
for (size_t i = 0; i != rows; ++i) 
    matrix2d[i] = &matrix1d[i * cols]; 

int v1 = matrix1d[r * cols + c]; 
int v2 = matrix2d[r][c]; 
+1

你也可以做一些很酷的技巧,比如常量行交換(對於某些矩陣簡化算法非常有用) – 2014-10-28 12:27:55

1

我建議你使用std::vector,因爲它本質上是動態的,易於使用。

int row; 
int col; 
std::vector< std::vector<int> > twoDMatrix(row, std::vector<int>(col)); 

注意,如果你正在使用std::vector不要忘記添加#include<vector>

0

const int row = 256; const int col = 256; vector<vector<int> > matrix2D(row, (col,0)); /*通過這一點,我們可以說,我們有一個二維矩陣是256 * 256,並且所有的元素都爲0 */