size() //返回容器中元素的个数
empty() //判断容器是否为空
resize(int num) //重新指定容器的长度num,容器变长,则以默认值填充新位置,如果容器变短,则末尾超出容器长度的元素被删除
resize(int num,elem) //重新制定容器的长度为num,若容器变长,则以elem值填充位置,如果容器便短,则删除超出长度的元素
capacity() 容器的容量
reserve(int len) //容器预留len个元素长度,预留位置不初始化,元素不可访问
#include <iostream> #include <vector> using namespace std; void show(vector<int> &v){ for(vector<int>::const_iterator it =v.begin();it != v.end();it ++){ //迭代器的本质是地址 cout << *it<<" "; } cout<<endl; }; void test01(){ int arry[] ={10,20,30,40,50,60,70}; vector<int> v1(arry,arry+sizeof(arry)/sizeof(arry[0])); cout<<"元素个数:"<<v1.size()<<endl; if (v1.empty()){ cout<<"vector是空"<<endl;} else cout<<"vector不为空"<<endl; v1.resize(10); //resize()中的int类型是指元素个数 show(v1); v1.resize(15,11); show(v1); cout<<"容器的容量"<<v1.capacity()<<endl; v1.reserve(30); //size一定小于容量 show(v1); cout<<"容器的容量"<<v1.capacity()<<endl; } int main() { test01(); return 0; }
at(int idx) 返回idx的索引数据,如果越界抛出out_of_range异常
operator[] 返回索引idx所指的数据,越界时,运行直接报错
front() 返回容器中第一个元素
back()返回容器中最后一个元素
#include <iostream> #include <vector> #include<cstring> using namespace std; void test(){ int arry[] = {0,1,2,3,4}; vector<int> v(arry,arry+sizeof(arry)/sizeof(arry[0])); int a = v.at(9); cout<<a<<endl; cout<<v.front()<<" "; cout<<v.back()<<endl; cout<<"________"<<endl; a = v[9]; cout<<a<<endl; } int main() { try{ test();} catch (out_of_range){ cout<<"out of range"; } return 0; }
insert(const_iterator pos,int count,ele); 从pos插入count个ele
push_back(ele); 尾部插入元素
pop_back(); 删除最后一个元素
erase(const_iterator start,const_iterator end);删除迭代器 start-end之间的元素
clear() ; 清除所有元素
#include <iostream> #include <vector> using namespace std; void show(vector<int> &v){ for(vector<int>::const_iterator it =v.begin();it != v.end();it ++){ //迭代器的本质是地址 cout << *it<<" "; } cout<<endl; }; void test01(){ vector<int> v; v.push_back(10); v.push_back(20); v.insert(v.begin(),30);//从头部插入一个元素 show(v); v.insert(v.end(),40);//从尾部插入一个元素 show(v); v.insert(v.begin()+2,100);//可以随机访问的类型,可以采用+元素个数来偏移 show(v); v.erase(v.begin());//删除第一个元素 show(v); v.erase(v.begin()+2,v.end());//删除从头部的两个元素 show(v); v.clear(); cout<<"v.size = " << v.size()<<endl; } int main() { test01(); return 0; }