二维vector 的定义及使用
作者:
cassie
,
2021-11-26 12:47:31
,
所有人可见
,
阅读 776
#include<bits/stdc++.h>
using namespace std;
int main(){
vector< vector<int> > array;
for (int i = 0; i < 5; i++)
{
array.push_back(vector<int>());//不断往array里加行
}
for (int i = 0; i < array.size(); i++)//行
{
for (int j = 0; j < 5; j++)//添加5列
{
array[i].push_back(i + j);
}
}
for (int i = 0; i < array.size(); i++)
{
for (int j = 0; j < 5; j++)
{
cout << array[i][j] << " ";//使用下标访问
}
cout << endl;
}
return 0;
}
初始化
第一种
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector< vector<int> > a(n, vector<int>(2*n, 0));
for(int i = 0; i < n ; i ++){
for(int j = 0; j < 2 * n; j ++) cout << a[i][j] <<" ";
cout << endl;
}
return 0;
}
第二种
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<vector<int> >vv;
for(int c = 1; c <= n; c++)
vv.push_back(vector<int>(n,0));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << vv[i][j] << " ";
}
cout << endl;
}
return 0;
}