STL四大重要组件

  1 /* STL四大重要组件 */
  2 
  3 
  4 #include<iostream>
  5 #include<vector>
  6 #include<algorithm>
  7 #include<functional>
  8 
  9 using std::function;// 使用仿函数
 10 
 11 using namespace std;
 12 
 13 // 容器使用大约20%
 14 // 迭代器使用大约10%
 15 // 算法使用大约50%
 16 // 仿函数使用大约5%
 17 
 18 void main()
 19 {
 20     vector<int> myv;// 容器,堆上
 21     myv.push_back(10);
 22     myv.push_back(11);
 23     myv.push_back(12);
 24     myv.push_back(13);
 25     
 26     int a[5] = {1,2,3,4,5};// 容器,栈上
 27     for_each(myv.begin(),myv.end(),[](int x){cout << x << endl;})// 算法
 28     for_each(a,a+5,[](int x){cout << x << endl;};);// 算法
 29 
 30 
 31     cin.get();
 32 }
 33 
 34 //-----------------------------------------------------------------------------
 35 
 36 /* 迭代器 */
 37 void main()
 38 {
 39     vector<int> myv;// 容器,堆上
 40     myv.push_back(10);
 41     myv.push_back(11);
 42     myv.push_back(12);
 43     myv.push_back(13);
 44 
 45     auto ib = myv.begin();// ib 本质就是智能指针
 46     auto ie = myv.end();
 47     for(;ib!=ie;ib++)// 正向迭代器
 48     {
 49         cout << *ib << endl;// 重载了 *
 50     }
 51 
 52     auot rb = myv.rbegin();
 53     auto re = myv.rend();
 54     for(;rb!=re;rb++)// 反向迭代器
 55     {
 56         cout << *rb << endl;// 重载了 *
 57     }
 58 
 59 
 60     cin.get();
 61 }
 62 
 63 //-----------------------------------------------------------------------------
 64 
 65 /* 仿函数 */
 66 
 67 bool less11(int x)
 68 {
 69     return x < 11;
 70 }
 71 
 72 struct GREATER// 仿函数实现函数的功能,重载类或者重载类模板
 73 {
 74     bool operator()(int numleft,int numright)
 75     {
 76         return numleft > numright;    
 77     }
 78 };
 79 
 80 
 81 void main()
 82 {
 83     vector<int> myv;// 容器,堆上
 84     myv.push_back(10);
 85     myv.push_back(11);
 86     myv.push_back(12);
 87     myv.push_back(13);
 88 
 89 // 找出小于11的
 90     
 91     // 从头到尾开始找到第一个小于11的值
 92     //auto ifind = find_if(myv.begin(),myv.end(),bind1st(greater<int>(),11));
 93     
 94     GREATER g1;
 95     auto ifind = find_if(myv.begin(),myv.end(),bind1st(g1,11));
 96     
 97 
 98     auto ifind = find_if(myv.begin(),myv.end(),less11);
 99 
100 
101     // 从10-13 找到第一个符合条件的  返回值为true
102     
103 
104 
105     cout << *ifind << endl;
106 
107 
108     cin.get();
109 }

 

posted on 2015-06-13 10:07  Dragon-wuxl  阅读(287)  评论(0)    收藏  举报

导航