Chinaunix首页 | 论坛 | 博客
  • 博客访问: 335992
  • 博文数量: 100
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 521
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-31 11:37
个人简介

活到老,学到老

文章分类

全部博文(100)

文章存档

2018年(1)

2017年(2)

2016年(11)

2015年(82)

2014年(4)

我的朋友

分类: C/C++

2015-07-02 14:36:20


点击(此处)折叠或打开

  1. #include<iostream>
  2. #include<vector>
  3. #include<numeric>
  4. using namespace std;

  5. void Travel1(vector<int> &v)
  6. {
  7.     for(int i=0;i<(int)v.size();++i)
  8.     {
  9.         cout<<v.at(i)<<" ";
  10.     }
  11.     cout<<endl;

  12.     return ;
  13. }

  14. void Travel2(vector<int> &v)
  15. {
  16.     vector<int>::iterator it;
  17.     it = v.begin();
  18.     while( v.end())
  19.     {
  20.         cout << *it << ' ';
  21.         ++it;
  22.     }
  23.     cout << endl;

  24.     return ;
  25. }

  26. void Travel3(vector<int> &v)
  27. {
  28.     vector<int>::reverse_iterator rit;
  29.     for(rit=v.rbegin();rit!=v.rend();rit++)
  30.     {
  31.         cout<<*rit<<" ";
  32.     }
  33.     cout<<endl;
  34.     return ;
  35. }


  36. int main(int argc,char **argv)
  37. {
  38.     vector<int> v;
  39.     vector<int> v1;
  40.     for(int i=0;i<10;i++)
  41.     {
  42.         v.push_back(i);//在最后插入
  43.     }
  44.     for(int i=10;i>=0;i--)
  45.     {
  46.         v1.push_back(i);//在最后插入
  47.     }
  48.     //元素查询
  49.     cout << "第一个元素的值是:" << v.front() << endl;
  50.     cout << "最后一个元素的值是:" << v.back() << endl;
  51.     cout << "下标为1的元素的值是:" << v.at(1) << endl;
  52.     cout << "下标为3的元素的值是:" << v[3] << endl;

  53.     //元素插入删除
  54.     v.pop_back();//在最后删除
  55.     v.insert(v.begin()+4,10);//在指定位置插入
  56.     v.erase(v.begin()+3);//在指定位置删除
  57.     v.erase(v.end()-3);

  58.     cout<<"v.size="<<v.size()<<endl;
  59.     cout<<"v.empty()"<<v.empty()<<endl;

  60.     //v.clear();//清空

  61.     v.swap(v1);//v与v1交换
  62.     Travel1(v);
  63.     Travel2(v1);
  64.     Travel3(v1);

  65.     //accumulate(v.begin(),v.end(),0),把从 v.begin() 开始到 v.end()结束所有的元素加到 0上面去
  66.     cout << accumulate(v.begin(),v.end(),0) << endl;
  67.     return 0;
  68. }

阅读(957) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~