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

2021/8/17 11:06:07

本文主要是介绍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 }

 



这篇关于C++ //STL---常用算法 //常用遍历 for_each //transform的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程