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] C++ 中vector的使用方法
[2] c++中vector的用法详解