根據《ACM程序設計》寫的,用實例展示vector用法。
方法:push_back(), insert(), erase(), clear(), size(), empty();
算法:reverse(), sort(), accumulate().
1 #include <vector>
2 #include <iostream>
3 #include <algorithm> //sort、reverse算法
4 #include <numeric> //accumulate算法
5 using namespace std;
6 template <typename T>
7 void printVec(const vector<T> &v){ //函數模板輸出向量
8 for(int i=0;i<v.size();i++)
9 cout<<v[i]<<' ';
10 cout<<endl<<endl;
11 }
12
13 int main(){
14 vector<int> iv; //定義向量
15 iv.push_back(2); //尾部追加新元素
16 iv.push_back(7);
17 iv.push_back(3);
18 iv.push_back(4);
19 iv.push_back(1);
20 iv.push_back(9);
21 cout<<iv[2]<<endl; //下標訪問元素
22
23 vector<double> dv(3); //定義向量
24 cout<<dv[2]<<endl; //默認值為0
25
26 vector<double> dv1(6,7.18); //定義向量
27 cout<<dv1[2]<<endl; //默認值為7.18
28
29 vector<int>::iterator it; //迭代器輸出向量
30 for(it=iv.begin();it!=iv.end();it++)
31 cout<<*it<<' ';
32 cout<<endl;
33 cout<<accumulate(iv.begin(),iv.end(),0);
34 //使用accumulate求和
35
36 iv.insert(iv.begin(),8); //在首元素前插入8
37 iv.insert(iv.begin()+2,6); //在第3個元素前插入6
38 iv.insert(iv.end(),5); //在末元素前插入5
39 printVec(iv); //調用printVec函數
40
41 dv1.erase(dv1.begin()+3); //刪除一個元素
42 printVec(dv1);
43
44
45 dv1.erase(dv1.begin()+2,dv1.end()-1); //刪除多個元素(包括左值不包括右值)
46 printVec(dv1);
47 cout<<endl;
48
49 dv1.clear(); //清空向量
50 cout<<dv1.size()<<' '<<dv1.empty()<<endl;
51 //返回元素個數/向量是否為空
52
53 reverse(iv.begin(),iv.end()); //使用reverse反向排列算法
54 printVec(iv);
55
56 sort(iv.begin(),iv.end()); //使用sort升序排列
57 printVec(iv);
58 return 0;
59 }