编程语言
首页 > 编程语言> > C++ //STL---常用算法 //常用遍历 for_each //transform

C++ //STL---常用算法 //常用遍历 for_each //transform

作者:互联网

  1 //STL---常用算法  
  2 //常用遍历 for_each
  3 //transform
  4 #include<iostream>
  5 #include<string>
  6 #include<functional>
  7 #include<algorithm>
  8 #include<vector>
  9 
 10 //using namespace std;
 11 using namespace std;
 12 //普通函数
 13 void print01(int val)
 14 {
 15     cout << val << " ";
 16 }
 17 
 18 //仿函数
 19 class print02
 20 {
 21 public:
 22     void operator()(int val)
 23     {
 24         cout << val << " ";
 25     }
 26 };
 27 
 28 
 29 void test01()
 30 {
 31     vector<int>v;
 32     for (int i = 0; i < 10; i++)
 33     {
 34         v.push_back(i);
 35     }
 36 
 37     for_each(v.begin(), v.end(), print01);
 38     cout << endl;
 39 
 40     for_each(v.begin(), v.end(), print02());
 41     cout << endl;
 42 }
 43 
 44 //transform
 45 //搬运的
 46 class Transform
 47 {
 48 public:
 49     int operator()(int v)
 50     {
 51         return v + 100;
 52     }
 53 };
 54 
 55 //void print03(int vT)
 56 //{
 57 //    cout << vT << " ";
 58 //}
 59 class print03
 60 {
 61 public:
 62     void operator()(int val)
 63     {
 64         cout << val << " ";
 65     }
 66 };
 67 
 68 
 69 void test02()
 70 {
 71     vector<int>v;
 72     for (int i = 0; i < 10; i++)
 73     {
 74         v.push_back(i);
 75     }
 76     cout << "v容器数据:" << endl;
 77 
 78     for_each(v.begin(), v.end(), print03());
 79     cout << endl;
 80 
 81     //cout << "v容器数据:" << endl;
 82     //for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
 83     //{
 84     //    cout << *it << " ";
 85     //}
 86     //cout << endl;
 87 
 88 
 89      vector<int>vTarget;   //目标容器
 90      vTarget.resize(v.size());  //目标容器需要提前开辟空间
 91 
 92     transform(v.begin(), v.end(), vTarget.begin(), Transform());
 93 
 94     cout << "vTarget容器数据:" << endl;
 95     for_each(vTarget.begin(), vTarget.end(), print03());
 96     cout << endl;
 97 }
 98 int main()
 99 {
100     //test01();
101     test02();
102     system("pause");
103     return 0;
104 }

 

标签:begin,常用,end,cout,vTarget,STL,transform,int,include
来源: https://www.cnblogs.com/Bytezero/p/15151362.html