【C/C++】vector 动态二维数组

时间:2022-10-05 14:01:00
  1. 声明
vector<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);
  1. 遍历
void 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;
}
}
  1. 自己写了一个初始化二维动态数组

    这个填写的思路就是,从里面往外面填,因为外面只能填vector,只有里面的可以用insert函数来填数字
   string str1, str2;
cin >> str1 >> str2;
int len1 = str1.length(); //i
int len2 = str2.length(); //j
vector<vector<int>> dp;
//根据长度开创一个动态二维数组 //vector的填写
vector<int> tmp;
tmp.insert(tmp.begin(), len2, 0);
dp.insert(dp.begin(), len1, tmp); vector<int>::iterator it;
vector<vector<int>>::iterator iter;
vector<int> vec_tmp; cout << "Use iterator : " << endl;
for(iter = dp.begin(); iter != dp.end(); iter++)
{
vec_tmp = *iter;
for(it = vec_tmp.begin(); it != vec_tmp.end(); it++)
cout << *it << " ";
cout << endl;
}