vector练习笔记

 1 //vector 当作数组应用
 2 #include "stdafx.h"
 3 #include<iostream>
 4 #include<vector>                        //第一步包含头文件
 5 using std::vector;                      //第二步命名空间
 6 int _tmain(int argc, _TCHAR* argv[]){
 7     vector<int> v;                      //第三部实例化一个vector 指定类型int
 8     v.push_back(1);                     //用push_back将元素放入容器
 9     v.push_back(2);
10     v.push_back(3);
11     for (int i = 0; i < 3; i++){
12         std::cout << v[i] << std::endl; //用下标的方式打印出来
13     }
14     system("pause");
15     return 0;
16 }
 1 //包含相关头文件
 2 #include "stdafx.h"
 3 #include<iostream>
 4 #include<cstdlib>
 5 #include<vector>
 6 #include<iomanip>
 7 #define SETW 10
 8 
 9 //相关命名空间
10 using std::vector;
11 using std::cout;
12 using std::endl;
13 using std::setw;
14 
15 //打印向量中的信息
16 void PrintVectorInfo(vector<int>& v){
17     cout << setw(SETW) << "Element" << setw(SETW) << "Size";
18     cout << setw(SETW) << "Capacity" << endl;
19         //iterator可以理解为一个指针类型
20     for (vector<int>::iterator it = v.begin(); it != v.end(); it++){
21         //此时的it为容器元素地址,*it取出这个地址的值。
22         //size函数返回目前持有元素个数
23         //capacity表明当前可容纳最大元素个数
24         cout << setw(SETW) << (*it) << setw(SETW) << v.size();
25         cout << setw(SETW) << v.capacity() << endl;
26     }
27     cout << endl;
28 }
29 
30 
31 //主函数
32 int _tmain(int argc, _TCHAR* argv[]){
33     //定义一个Vector
34     vector<int> vecintObj;
35     //定义几个变量
36     int a = 11, b = 22, c = 33;
37     //将变量a加入到向量中
38     vecintObj.push_back(a);
39     cout << "push back: a=" << a << endl;
40     //将变量b,c加入到向量中
41     vecintObj.push_back(b);
42     cout << "push back: b=" << b << endl;
43     vecintObj.push_back(c);
44     cout << "push back: c=" << c << endl;
45     PrintVectorInfo(vecintObj);
46     //移除一个元素
47     vecintObj.pop_back();
48     cout << "pop Back......" << endl;
49     PrintVectorInfo(vecintObj);
50     //移除一个元素
51     vecintObj.pop_back();
52     cout << "pop Back......" << endl;
53     PrintVectorInfo(vecintObj);
54     //移除最后一个元素
55     vecintObj.pop_back();
56     cout << "pop Back......" << endl;
57     PrintVectorInfo(vecintObj);
58     //清除所有元素
59     vecintObj.clear();
60     cout << "Clear All Elements" << endl;
61     getchar();
62     return 0;
63 }

 

posted @ 2016-01-20 15:16  天还是那么蓝  阅读(218)  评论(1编辑  收藏  举报