C++ vector 容器淺析[05] ~ 二維數組(二維陣列)兩種定義方法
C++ vector 容器淺析[05] ~ 二維數組(二維陣列)兩種定義方法
資料來源: https://www.runoob.com/w3cnote/cpp-vector-container-analysis.html
純C++線上編譯測試: https://www.tutorialspoint.com/compile_cpp_online.php
純C 線上編譯測試: https://www.tutorialspoint.com/compile_c_online.php
方法01:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int N=5, M=6;
vector< vector<int> > obj(N); //定义二维动态数组大小5行
for(int i =0; i< obj.size(); i++)//动态二维数组为5行6列,值全为0
{
obj[i].resize(M);
}
for(int i=0; i< obj.size(); i++)//init二维动态数组
{
for(int j=0;j<obj[i].size();j++)
{
obj[i][j]=i+j;
}
}
for(int i=0; i< obj.size(); i++)//输出二维动态数组
{
for(int j=0;j<obj[i].size();j++)
{
cout<<obj[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
方法02:
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int N=5, M=6;
vector<vector<int> > obj(N, vector<int>(M)); //定义二维动态数组5行6列
for(int i=0; i< obj.size(); i++)//init二维动态数组
{
for(int j=0;j<obj[i].size();j++)
{
obj[i][j]=i+j;
}
}
for(int i=0; i< obj.size(); i++)//输出二维动态数组
{
for(int j=0;j<obj[i].size();j++)
{
cout<<obj[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}