鱼C论坛

 找回密码
 立即注册
查看: 1534|回复: 0

[技术交流] Vector容器

[复制链接]
发表于 2019-7-16 19:28:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Julia999 于 2019-7-30 20:43 编辑
模板向量的一些其他成员函数:
(1)重载操作符[]返回容器中某一个元素,参考两个版本:const和非const
(2)函数frond()和back()返回第一个和最后一个元素
(3)函数insert()在一个给定的位置插入一个新的元素
(4)功能push_back()和pop_back()添加或删除最后一个成员
事例:
  1. #include<iostream>
  2. #include<algorithm>
  3. #include<iterator>
  4. using namespace std;

  5. int main(int argc,const char *argv[])
  6. {
  7.      const int Size=6;
  8.      int array[Size]={1,2,3,4,5,6};
  9.      //声明一个int类型集合的容器,并用数组a对容器进行初始化
  10.      vector<int> v(array,array+Size);    //存array到array+size中的元素
  11.      cout<<"First element:"<<v.front()<<"\nLast element"<<v.back()<<endl;
  12.      //通过下标操作符和at函数来修改容器中元素内容
  13.      //注意二者的区别,后者更安全,at函数会检查下标是否越界。
  14.      v[1]=7;
  15.      //at会抛出异常(如果越界)
  16.      v.at(2)=10;
  17.      //在第二个元素位置插入22元素
  18.      v.insert(v.begin()+1,22);
  19.      //尾部添加元素19
  20.      v.push_back(19);
  21.      //声明一个迭代器(必须vector<int>::iterator)
  22.      vector<int>::iterator iter;
  23.      iter=v.begin();  //迭代器指向容器第一元素的位置
  24.      while(iter!=v.end())
  25.      {
  26.             cout<<*iter<<endl;  //类似指针解引运算符
  27.             iter++;  //迭代器向后移动
  28.      }
  29.      //查找元素5(不是第5个)的位置,并返回其迭代器
  30.      iter=find(v.begin(),v.end(),22);
  31.      if(iter!=v.end())
  32.      {
  33.              cout<<"the location:"<<(iter-v.begin())<<endl;
  34.      }
  35.      else
  36.     {
  37.             cout<<"not found"<<endl;
  38.     }
  39.     //系统最大容量
  40.     cout<<"The max size of the vector is:"<<v.max_size();
  41.     //当前最大容量
  42.     cout<<"The current capacity is:”<<v.capacity()<<endl;
  43.     try
  44.    {
  45.           v.at(1)=777;   //越界 抛出异常
  46.     }
  47.     catch(out_of_range &e)
  48.     {
  49.           cout<<"Exception:"<<e.what();
  50.     }
  51.     v.erase(v.begin());   //清除第一个元素
  52.     v.erase(v.begin(),v.end());   //清除所有元素
  53.     cout<<"After erase,v"<<(v.empty()?"is:":"is not")<<"empty"<<endl;
  54.     v.clear();  //清空容器
  55.     cout<<"After clear,v"<<(v.empty()?"is":"is not")<<“empty”<<endl;
  56.     return 0;
  57. }
复制代码






想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 07:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表