1 #include <algorithm> 2 3 #include <iostream> 4 #include <vector> 5 #include <string> 6 7 using std::vector; 8 using std::string; 9 using std::cout; 10 using std::endl; 11 12 template<class InputIter, class Func> 13 Func LTM_for_each(InputIter first, InputIter last, Func func) 14 { 15 while (first != last) 16 { 17 func(*first); 18 ++first; 19 } 20 return func; 21 } 22 23 void helperFunction(string& str) 24 { 25 str += ".cpp"; 26 } 27 28 void print(vector<string> vec) 29 { 30 vector<string>::iterator iter; 31 for (iter = vec.begin(); iter != vec.end(); iter++) 32 { 33 cout << *iter << endl; 34 } 35 cout << ‘\n‘; 36 } 37 38 int main(void) 39 { 40 vector<string> vec; 41 vec.push_back("a"); 42 vec.push_back("b"); 43 vec.push_back("c"); 44 vec.push_back("d"); 45 print(vec); 46 47 // for_each(vec.begin(), vec.end(), helperFunction); 48 LTM_for_each(vec.begin(), vec.end(), helperFunction); 49 print(vec); 50 51 return 0; 52 }
时间: 2024-10-10 15:35:02