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 }
for_each第三個參數傳入的是函數名稱
通過模板生成代碼後的函數指針,for_each需要調用,可以看看STL的for_each函數的源碼
===========================================
// 你的需求
void printName( const CStudent& _s )
{
std::cout<< _s.name << std::endl;
}
std::vector<CStudent> stu_list;
std::for_each( stu_list.begin(), stu_list.end(), printName );
......,print<int>);