一、vector 容器嵌套
1、vector中嵌套一个vector容器,来表示一个二维数组
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
void Test01()
{
vector<vector<int>> v;
// 创建小容器
vector<int> v1;
vector<int> v2;
vector<int> v3;
vector<int> v4;
// 向小容器中添加数据
for (int i = 0; i < 4; i++)
{
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
v4.push_back(i + 4);
}
// 将小容器中数据加入到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
// 通过大容器将所有的数据进行遍历
for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++)
{
for (vector<int>::iterator it2 = (*it).begin(); it2 != (*it).end(); it2++)
{
cout << (*it2) << " ";
}
cout << endl;
}
}
int main() {
Test01();
cin.get();
}
二、vector 应用
1、vector用来创建动态数组对象,其相当于一个容器。
vector不是一个类,而是一个类模板。用vector定义动态数组的形式为 :
vector<元素类型> 数组对象名(数组长度) //数组长度可有可无。
vector<int> array; //创建一维整型数组对象array
vector<vector<int>> test //创建二维整型数组对象test
2、vector中常见应用
array.size() // array数组的长度值。
test[0].size() //二维数组第一行的列数
array.push_back(num) //在数组array尾部添加数据num
array.pop_back() //去掉数组的最后一个数据。
array.empty() //判断array数组是否为空
array.clear() //清空array数组
array[k] //访问数组的元素array[k]的值
test[i][j] //访问二维数组的元素test[i][j]
3、vector的用法实例
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> test0 ;
vector<vector<int>> test1 ; //test1为整型的二维数组。
//vector<vector<int>> test2 ;
int a1[]={1,2,3,4}, a2[]={5,6,7,8}, a3[]={9,10,11,12} ;
test0.push_back(100) ;
test0.push_back(200) ;
test0.push_back(300) ;
//test0.size()为test0数组的长度值。
cout<<"The number of test0 is "<<test0.size()<<endl ;
cout<<"the vector of test0 is \n";
for(int i=0; i<test0.size();++i){
cout<<test0[i]<<endl;
}
test0.pop_back();
test0.pop_back();
cout<<"test the funcation of pop_back \n";
for(int t=0 ;t<test0.size();++t){
cout<<test0[t]<<endl;
}
/* vector<int>(a1,a1+3)表示取动态数组a1[]中的前三个数据。
* 在下面这段代码中是分别将a1[],a2[]数组的前三个数据,存放
* 到二维数组test1中作为其第一,第二行的数据。
*/
test1.push_back(vector<int>(a1,a1+3));
test1.push_back(vector<int> (a2,a2+3));
cout<<"the vector of test1 is :"<<endl;
for(int k=0;k<test1.size();++k){
for(int j=0;j<test1[0].size();++j){
cout<<test1[k][j];
}
cout<<endl;
}
}
三、多维数组的排序
1、在多维数组中,用 sort 函数排序时,默认是按每一维的首元素进行升序的排序。
2、可以指定按照每一维数组的第几个元素来进行排序。
3、可以指定按多个条件进行排序。
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
// 指定按每维数组的第二个元素进行升序排序
bool cmp(vector<int> v1, vector<int>v2)
{
return v1[1] < v2[1];
}
void PrintVal(const vector<vector<int>>& res)
{
for (auto &i : res)
{
for (int j : i)
{
cout << j << " ";
}
cout << endl;
}
}
int main()
{
vector<vector<int>> res = { {2,5},{1,8},{0,2},{9,6} };
cout << "原二数组为:\n";
PrintVal(res);
cout << endl;
//默认按每维数组升序排列
sort(res.begin(), res.end());
cout << "按默认规则排序为:\n";
PrintVal(res);
cout << endl;
//按指定规则排序
sort(res.begin(), res.end(),cmp);
cout << "按指定规则排序为:\n";
PrintVal(res);
cout << endl;
system("pause");
return 0;
}
参考资料:
[1] C++ 中vector的使用方法
[2] c++中vector的用法详解