for_each()事實上是個 function template,其實質以下 [effective STL item 41]ios
template<typename InputIterator, typename Function> Function for_each(InputIterator beg, InputIterator end, Function f) { while(beg != end) f(*beg++); }
能看懂吧!!!
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { void operator () (int i) { cout<<i<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play()); }
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { Play() { cout<<"new a Play"<<endl; } Play(const Play&) { cout<<"new a copy Play"<<endl; } void operator () (int i) { cout<<i<<endl; } ~Play() { cout<<"dispose a Play"<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play()); cout<<"See something"<<endl; }
結果以下:
new a Play
1
3
4
5
new a copy Play
dispose a Play
dispose a Play
See something
能夠看到這個過程有兩個Play對象生成,可是,用於輸出元素的倒是第一個對象(重載() 操做符),爲何?
這時候回去看for_each的源碼,就會發現,它的返回值是function,以個人猜想,應該是這樣的。函數
Play() 生成一個臨時的匿名的Play對象,傳入for_each 函數裏,而後執行完for_each 函數後,return一個function時,Play用複製構造函數生成一個Play對象,而後兩個Play對象的生命週期都結束,因而依次銷燬。spa
能夠經過構造函數的技巧傳入參數code
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { const char* str; Play(const char* s):str(s) {} void operator () (int i) { cout<<str<<i<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play("Element:")); //其實 仍是關鍵看 Play函數如何實現的! }
結果:
經過mem_fun_ref() 這個funtion adapater 將 member funtion 轉成 function object。component
先到這裏吧 下次 繼續 !!!!對象