|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Julia999 于 2019-7-30 20:43 编辑 模板向量的一些其他成员函数:
(1)重载操作符[]返回容器中某一个元素,参考两个版本:const和非const
(2)函数frond()和back()返回第一个和最后一个元素
(3)函数insert()在一个给定的位置插入一个新的元素
(4)功能push_back()和pop_back()添加或删除最后一个成员 事例:- #include<iostream>
- #include<algorithm>
- #include<iterator>
- using namespace std;
- int main(int argc,const char *argv[])
- {
- const int Size=6;
- int array[Size]={1,2,3,4,5,6};
- //声明一个int类型集合的容器,并用数组a对容器进行初始化
- vector<int> v(array,array+Size); //存array到array+size中的元素
- cout<<"First element:"<<v.front()<<"\nLast element"<<v.back()<<endl;
- //通过下标操作符和at函数来修改容器中元素内容
- //注意二者的区别,后者更安全,at函数会检查下标是否越界。
- v[1]=7;
- //at会抛出异常(如果越界)
- v.at(2)=10;
- //在第二个元素位置插入22元素
- v.insert(v.begin()+1,22);
- //尾部添加元素19
- v.push_back(19);
- //声明一个迭代器(必须vector<int>::iterator)
- vector<int>::iterator iter;
- iter=v.begin(); //迭代器指向容器第一元素的位置
- while(iter!=v.end())
- {
- cout<<*iter<<endl; //类似指针解引运算符
- iter++; //迭代器向后移动
- }
- //查找元素5(不是第5个)的位置,并返回其迭代器
- iter=find(v.begin(),v.end(),22);
- if(iter!=v.end())
- {
- cout<<"the location:"<<(iter-v.begin())<<endl;
- }
- else
- {
- cout<<"not found"<<endl;
- }
- //系统最大容量
- cout<<"The max size of the vector is:"<<v.max_size();
- //当前最大容量
- cout<<"The current capacity is:”<<v.capacity()<<endl;
- try
- {
- v.at(1)=777; //越界 抛出异常
- }
- catch(out_of_range &e)
- {
- cout<<"Exception:"<<e.what();
- }
- v.erase(v.begin()); //清除第一个元素
- v.erase(v.begin(),v.end()); //清除所有元素
- cout<<"After erase,v"<<(v.empty()?"is:":"is not")<<"empty"<<endl;
- v.clear(); //清空容器
- cout<<"After clear,v"<<(v.empty()?"is":"is not")<<“empty”<<endl;
- return 0;
- }
复制代码
|
|