C++动态分配数组/向量(一维,二维)

new 方法

一维:

int * a = new int [n];

...

delete [] a;  // can't use "delete a"

 

二维(m×n):

int **a = new int * [m];

for (int i = 0; i < m; ++i)

  a[i] = new int [n];

...

for (int i = 0; i < m; ++i)

  delete [] a[i];

delete [] a;

 

Vector 方法:

一维:

vector<int> a(n);  // 指定容器大小为n

vector<int> a(n, x);  // 指定容器大小为n,并初始化所有元素为x

 

二维:

vector<vector<int> > a(m, vector<int>(n));  // m行n列的二维数组,可以直接用a[i][j]访问

posted on 2011-01-08 09:43  小虎无忧  阅读(2837)  评论(0编辑  收藏  举报

导航