1 #include <iostream>
  2 #include <cstdio>
  3 #include <vector>
  4 
  5 using namespace std;
  6 
  7 // 注意:vector在尾部添加或移动元素非常快,在中间操作非常耗时,因为它需要移动元素
  8 
  9 
 10 int main()
 11 {
 12     vector<int> v1;
 13     //push_back
 14     v1.push_back(1);
 15     //pop_back
 16     v1.push_back(2);
 17     // front,back,可以做左值
 18     cout<<v1.front()<<endl;
 19     cout<<v1.back()<<endl;
 20     // 左值
 21     v1.back()=5;
 22 
 23     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
 24     {
 25         cout<<*it<<" ";
 26     }
 27     cout<<endl;
 28 
 29     v1.pop_back();
 30 
 31     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
 32     {
 33         cout<<*it<<" ";
 34     }
 35     cout<<endl;
 36 
 37 
 38     // 以上是直接初始化方式
 39     // 还有以下三种初始化方式
 40     vector<int> v2=v1;
 41 
 42     vector<int> v3(v1.begin(),v1.begin()+1);
 43     vector<int> v4(v1.begin(),v1.end());
 44 
 45     vector<int> v5(3,9);
 46 
 47     for(vector<int>::iterator it=v5.begin();it!=v5.end();++it)
 48     {
 49         cout<<*it<<" ";
 50     }
 51     cout<<endl;
 52 
 53 
 54     for(int i=0;i<=5;++i)
 55     {
 56         v1.push_back(i);
 57     }
 58 
 59     // 用迭代器,逆向遍历
 60     for(vector<int>::reverse_iterator it=v1.rbegin();it!=v1.rend();it++)
 61     {
 62         cout<<*it<<" ";
 63     }
 64     cout<<endl;
 65     // 正向
 66     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
 67     {
 68         cout<<*it<<" ";
 69     }
 70     cout<<endl;
 71 
 72 
 73     vector<int> v(10);
 74     cout<<v.size()<<endl;
 75 
 76     v.push_back(100);
 77 
 78     cout<<v.size()<<endl;
 79     for(vector<int>::iterator it=v.begin();it!=v.end();++it)
 80     {
 81         cout<<*it<<" ";
 82     }
 83     cout<<endl;
 84 
 85     // 删除
 86     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
 87     {
 88         cout<<*it<<" ";
 89     }
 90     cout<<endl;
 91     v1.erase(v1.begin(),v1.begin()+3);
 92     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
 93     {
 94         cout<<*it<<" ";
 95     }
 96     cout<<endl;
 97 
 98     v1.erase(v1.begin()+3);
 99     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
100     {
101         cout<<*it<<" ";
102     }
103     cout<<endl;
104 
105 
106     // 插入
107     v1.insert(v1.begin()+2,10);
108     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
109     {
110         cout<<*it<<" ";
111     }
112     cout<<endl;
113 
114     v1.insert(v1.begin()+1,3,33);
115     for(vector<int>::iterator it=v1.begin();it!=v1.end();++it)
116     {
117         cout<<*it<<" ";
118     }
119     cout<<endl;
120 
121 
122     return 0;
123 }

 

posted on 2020-01-28 17:35  带你AK,带你飞  阅读(127)  评论(0编辑  收藏  举报