for_each()事實上是個 function template,其實質如下 [effective STL item 41]
template<typename InputIterator, typename Function> Function for_each(InputIterator beg, InputIterator end, Function f) { while(beg != end) f(*beg++); }
能看懂吧!!!
Object Oriented 與for_each 搭配
1、不傳入參數,使用function object
#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對象的生命周期都結束,於是依次銷毀。
2、傳入參數
可以通過構造函數的技巧傳入參數
#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函數如何實現的! }
結果:
Element:1
Element:3
Element:4
Element:5
Member function 與 for_each 搭配
1、不傳入參數
通過mem_fun_ref() 這個funtion adapater 將 member funtion 轉成 function object。
先到這里吧 下次 繼續 !!!!