先看一个STL中for_each的用法:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <functional>
 5 #include <iterator>
 6 using namespace std;
 7 class Test
 8 {
 9 public:
10     Test(int _data = 0):data(_data){}
11     
12     void print(){cout<<"i am class Test"<< data<<endl;}
13     void add(int b){ data += b;}
14     int data;
15 };
16 
17 int val[] = {0,1,2,3,4,5,6};
18 int main()
19 {    Test t(3);
20     vector<int> ivec(val,val+7);
21     vector<Test> tvec;
22     copy(istream_iterator<int>(cin),istream_iterator<int>(),back_inserter(tvec));
23     /*这个地方是将int隐式转化为Test类型了,与本主题无关,使用ctrl+z结束输入*/
24     for_each(tvec.begin(),tvec.end(),Test::print);
25     for_each(ivec.begin(),ivec.end(),t.add);
26 }
View Code

相关文章:

  • 2022-02-25
  • 2021-11-15
  • 2022-02-23
  • 2021-09-17
  • 2022-12-23
  • 2021-12-19
  • 2021-07-24
猜你喜欢
  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2022-12-23
  • 2021-06-13
  • 2022-02-08
相关资源
相似解决方案