for_each示例

来源:互联网 发布:ubuntu挂载 编辑:程序博客网 时间:2024/06/03 21:46
[cpp] view plaincopyprint?
  1. void myfun1(int& i)  
  2. {  
  3.     std::cout << i << " ";  
  4. }  
  5.   
  6. void myfun2(int i, const char* prefix)  
  7. {  
  8.     std::cout << prefix << i << std::endl;  
  9. }  
  10.   
  11. struct mystruct1 {  
  12.     void operator() (int& i)  
  13.     {  
  14.         std::cout << i << " ";  
  15.     }  
  16. } myobject1;  
  17.   
  18. struct mystruct2 {  
  19.     const char* prefix_;  
  20.     mystruct2(const char* prefix): prefix_(prefix) {}  
  21.     void operator() (int& i) {  
  22.         std::cout << prefix_ << i << std::endl;  
  23.     }   
  24. };  
  25.   
  26. class myclass1  
  27. {  
  28. public:  
  29.     void operator() (int& i)  
  30.     {  
  31.         std::cout << i << " ";  
  32.     }  
  33. };  
  34.   
  35. class myclass2  
  36. {  
  37. public:  
  38.     const char* prefix_;  
  39.     myclass2(const char* prefix): prefix_(prefix){};  
  40.     void operator() (int& i)  
  41.     {  
  42.         std::cout << i << " ";  
  43.     }  
  44. };  
  45.   
  46. void test_for_each()  
  47. {  
  48.     int ar[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};  
  49.     std::vector<int> v(ar, ar + 9);  
  50.   
  51.     // 一个参数的普通函数  
  52.     std::cout << "myfunction1 output below: " << std::endl;  
  53.     for_each(v.begin(), v.end(), myfun1);  
  54.     std::cout << std::endl;  
  55.   
  56.     // 二个参数的普通函数  
  57.     std::cout << "myfunction2 output below: " << std::endl;  
  58.     for_each(v.begin(), v.end(), std::bind2nd(std::ptr_fun(myfun2), "i = "));  
  59.   
  60.     // 不带参的结构体  
  61.     std::cout << "mystruct1 output below: " << std::endl;  
  62.     for_each(v.begin(), v.end(), mystruct1());  
  63.     // for_each(v.begin(), v.end(), myobject1); // 这个方法也行.  
  64.     std::cout << std::endl;  
  65.   
  66.     // 带参的结构体  
  67.     std::cout << "mystruct2 output below: " << std::endl;  
  68.     for_each(v.begin(), v.end(), mystruct2("i = "));  
  69.   
  70.     // 不带参的类  
  71.     std::cout << "myclass1 output below: " << std::endl;  
  72.     for_each(v.begin(), v.end(), myclass1());  
  73.     std::cout << std::endl;  
  74.   
  75.     // 带参的类  
  76.     std::cout << "myclass2 output below: " << std::endl;  
  77.     for_each(v.begin(), v.end(), myclass2("i = "));  
  78.     std::cout << std::endl;  
  79. }  
0 0
原创粉丝点击