C++ 构建二维动态数组1
2
3
4
5
6int **p;
p = new int*[10]; //注意,int*[10]表示一个有10个元素的指针数组
for (int i = 0; i < 10; ++i)
{
p[i] = new int[5];
}
1.初始化
(1)利用Vector的push_back函数1
2
3
4
5
6
7
8
9
10
11
12
13
14vector<vector<int>> vec;
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
vector<int> b;
b.push_back(4);
b.push_back(5);
b.push_back(6);
vec.push_back(a);
vec.push_back(b);
(2)先定义好二维数组结构,在直接赋值1
2
3
4
5
6
7
8
9
10
11
12
13
14//得到一个5行3列的数组
//由vector实现的二维数组,可以通过resize()的形式改变行、列值
int i,j;
vector<vector<int>> array(5);
for (i = 0; i < array.size(); i++)
array[i].resize(3);
for(i = 0; i < array.size(); i++)
{
for (j = 0; j < array[0].size();j++)
{
array[i][j] = (i+1)*(j+1);
}
}
2.遍历
(1)利用迭代器1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21void reverse_with_iterator(vector<vector<int>> vec)
{
if (vec.empty())
{
cout << "The vector is empty!" << endl;
return;
}
vector<int>::iterator it;
vector<vector<int>>::iterator iter;
vector<int> vec_tmp;
cout << "Use iterator : " << endl;
for(iter = vec.begin(); iter != vec.end(); iter++)
{
vec_tmp = *iter;
for(it = vec_tmp.begin(); it != vec_tmp.end(); it++)
cout << *it << " ";
cout << endl;
}
}
(2)得到行、列大小,利用下标进行遍历1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17void reverse_with_index(vector<vector<int>> vec)
{
if (vec.empty())
{
cout << "The vector is empty!" << endl;
return;
}
int i,j;
cout << "Use index : " << endl;
for (i = 0; i < vec.size(); i++)
{
for(j = 0; j < vec[0].size(); j++)
cout << vec[i][j] << " ";
cout << endl;
}
}