(本文中的代碼直接粘貼在main函數下即可使用,部分代碼需在最后一行添加return 0;)
(用到的頭文件:#include <vector>
#include <iostream>
#include <iomanip> )
靜態二維數組的聲明:
C++中,創建2維數組可以使用最簡單的命令:
int a[2][3]={{1,2,3},{4,5,6}};
這種類型的數組在編譯時就已經分配好了內存,若我們要建立一個在運行時才決定大小的數組,則不能使用這種方法,如果用下列聲明創建數組:
int size; cin >> size; int matrix2D[size][size];
則會報錯:

在運行時才確定大小的數組叫做動態數組,動態數組不能夠在編譯時被分配空間。
一維動態數組的聲明:
若要讓系統在運行時才分配空間給數組,則需要使用特殊方法,下面是在C++中創建一維動態數組的方法:
1 int size; //聲明數組尺寸 2 int i; //循環控制變量 3 4 cout << "Please enter the size: "; 5 cin >> size; //輸入數組尺寸 6 int *matrix1D = new int[size]; //創建數組 7 8 for (i = 0; i < size; i++) 9 matrix1D[i] = rand() % 10; //按順序賦值 10 11 for (i = 0; i < size; i++) 12 cout << matrix1D[i] << " "; //按順序讀取 13 14 delete[] matrix1D; //釋放空間
運行結果如下:

在上述程序第6行的代碼中, new運算符返回第一個元素的地址,該地址被賦予指針matrix1D。
由於matrix1D指向數組中的第一個元素,*matrix1D即為數組第一個元素的值,但是在C/C++中,matrix1D[0]可以直接指代數組中的第一個元素,對於第二個元素,可以使用matrix1D[1]操作。
二維動態數組的聲明:
1 int size_row,size_column; 2 int r,c; 3 cout << "Please enter the size of row: "; 4 cin >> size_row; 5 cout << "\nPlease enter the size of column: "; 6 cin >> size_column; 7 8 int **matrix2D = new int*[size_row]; 9 for (r = 0; r < size_row; r++) 10 matrix2D[r] = new int[size_column]; //創建數組 11 12 for (r = 0; r < size_row; r++) 13 for (c = 0; c < size_column;c++) 14 matrix2D[r][c] = rand() % 10; //賦值 15 16 for (r = 0; r < size_row; r++) 17 { 18 cout << endl; 19 for (c = 0; c < size_column; c++) 20 { 21 cout << matrix2D[r][c] << " "; 22 } 23 } //讀取 24 25 for (int r = 0; r < size_row; r++) 26 { 27 delete matrix2D[r]; 28 matrix2D[r] = NULL; 29 } 30 delete[size_row]matrix2D; 31 matrix2D = NULL; //釋放
運行結果如下:

對於2維數組可以將其理解為幾個一維行向量的疊加。
代碼第8行中 , 聲明 matrix2D是列向量matrix2D[0] matrix2D[1] matrix2D[2]的指針,向量中的元素個數與總行數相等。
9,10行的循環表示這個列向量中的每個元素都是一個行向量的指針,即matrix2D[0]是行向量matrix2D[0][1] matrix2D[0][2] matrix2D[0][3] matrix2D[0][4]的指針,這個道理與一維動態數組一致。
使用二維動態數組時可以直接使用例如matrix2D[1][2]來指代第二行第3列的元素。
釋放2維動態數組時也與1維有所不同,除了上述代碼中的方法外,比較通用並且簡便的方法有:
for (int r = 0; r < size_row; r++) delete[] matrix2D[r]; delete[] matrix2D; //釋放
第1,2行先釋放每行中分配的空間 即指針數組(matrix2D[0] matrix2D[1] matrix2D[2])每個元素指向的數組,如(matrix2D[0][0],matrix2D[0][1],matrix2D[0][2],matrix2D[0][3],...,)。
第3行再釋放這個指針數組。
二維動態數組的建立也可以用模板類vector:
使用vector之前要加載頭文件#include <vector>
1 int row, column; 2 int r, c; 3 cout << "Please enter the row" << endl; 4 cin >> row; 5 cout << "Please enter the column" << endl; 6 cin >> column; 7 8 vector<vector<int> > vector2D(row, vector<int>(column)); 9 10 for (r = 0; r < row; r++) 11 { 12 for (c = 0; c < column; c++) 13 vector2D[r][c] = rand() % 10; 14 } 15 16 for (r = 0; r < row; r++) 17 { 18 for (c = 0; c < column; c++) 19 { 20 cout << setw(2)<< vector2D[r][c] ; 21 } 22 cout << endl; 23 }
使用方法如上,聲明時int后兩個> >中間一定要有空格,否則會被認為是重載。
