2011-12-21 73 views
0

假設我使用的std::copy功能與std::remove_if功能相似,......添加鉤子的最佳方式是什麼?特別是我想記錄複製的狀態。最後我想的東西相當於:std ::複製鉤子

for(from begin to end iterator) 
{ 
    do the copy of the container; 
    cout << "." << flush; 
} 

但使用std::copy

+0

我不明白的問題。你想要'copy_if'嗎? – Nawaz 2011-12-21 08:11:49

+3

我很確定他的意思是類似於下面的答案:在複製循環的每次迭代中調用某些函數,這是他的假代碼 – stijn 2011-12-21 08:32:00

回答

3

有相當多隻有一個辦法:包裝用自己的迭代器輸出迭代器的行爲如出一轍但從副本的觀點,但internalyy也做了鉤動作。 例如,這可能是一些運營商實現:

template< class T, bool constcv > 
class HookingIterator : public std::iterator< std::forward_iterator_tag, .... > 
{ 
public: 
    reference operator*() 
    { 
    dereference_hook(); 
    return *actual_iterator_member; 
    } 

    this_type& operator ++() 
    { 
    increment_hook(); 
    ++actual_iterator_member; 
    return *this; 
    } 
}; 
在構造

提供實際的迭代器,和std ::函數對象(或普通功能/界面的一些例子,如果你的編譯器不具備的std ::功能)。

1

你可以用迭代器在一個結構,在那裏你把你的鉤子,例如:

#include<list> 
#include<algorithm> 
#include<numeric> 
#include <iostream> 
#include <vector> 
#include <assert.h> 
using namespace std; 

template<typename T> 
struct wrap_{ 

    T i; 

    typedef typename T::value_type value_type; 
    typedef typename T::difference_type difference_type; 
    typedef typename T::iterator_category iterator_category; 
    typedef typename T::pointer pointer; 
    typedef typename T::reference reference; 

    wrap_(T i) : i(i){} 
    wrap_& operator++(){ 
     cout << "++" << endl; 
     i++; 
     return *this; 
    } 
    wrap_ operator++(int){ i++; return *this; } 

    difference_type operator-(wrap_ j){ 
     return i-j.i; 
    } 

    value_type& operator*(){ 
     cout << "*" << endl;  
     return *i; 
    } 

}; 

template<typename T> 
wrap_<T> wrap(T i){ 
    return wrap_<T>(i); 
} 

int main(){ 
    vector<int> V(5); 
    for (int i=0;i<V.size();i++) V[i]=i+1; 

    list<int> L(V.size()); 
    copy(wrap(V.begin()), wrap(V.end()), L.begin()); 
    assert(equal(V.begin(), V.end(), L.begin())); 
} 

輸出:

* 
++ 
* 
++ 
* 
++ 
* 
++ 
* 
++ 
+0

明確表示的意圖謝謝。在某些圖書館中是否有像這樣的課程,例如在提升? – 2011-12-21 08:38:34

+0

不幸的是,我不知道。 – Vlad 2011-12-21 08:59:04