2012-11-01 37 views
8

Python的itertools具有正襞iterables teeitertools.tee等價於Boost :: Range?

def tee(iterable, n=2): 
    it = iter(iterable) 
    deques = [collections.deque() for i in range(n)] 
    def gen(mydeque): 
     while True: 
      if not mydeque:    # when the local deque is empty 
       newval = next(it)  # fetch a new value and 
       for d in deques:  # load it to all the deques 
        d.append(newval) 
      yield mydeque.popleft() 
    return tuple(gen(d) for d in deques) 

我無法找到Boost::Range相當。我錯過了什麼,或者我應該自己推出?

+3

也許增加一個更好的純文本描述你想要什麼,不是每個人都可以理解在python中yield或list表達式是做什麼的。 – inf

+0

你有這個用例嗎? – filmor

+0

這已經有一段時間了,但是我們的想法是將迭代器複製到一組將使用不同操作的消費者(例如不同的線程)。類似於Unix中的「tee」命令。我最終採用了完全不同的方法,而不是複製輸入,我只是順序地應用操作(即複用它們)。 –

回答

1

itertools.tee非常適合在Python中無處不在的單遍迭代。例如Generators是單程,他們經常被使用。

但是,如果你已經有了list/deque,你不會使用itertools.tee,因爲它會涉及多餘的重複 - 你可以重複遍歷原始列表/ deque。 C++也有單程範圍的概念,例如Input Iterator,但它們並不是那麼普遍。這是典型C++程序的另一組目標的結果 - 儘可能地爲用戶提供最大的性能。如果你願意,這是另一種心態。

爲了說明這一點,讓我們比較boost::transformeditertools.imap(或generator expressions):

他們都通過提供給「棱鏡」鑑於輸入序列。 itertools.imap回報單次迭代,而的boost ::轉化回報遠程視圖具有同一類別的輸入範圍 - 即,如果你想通過Random Access Range作爲輸入,你會得到隨機存取範圍作爲結果。

另一個事實是,C++默認使用value semantics,而python具有指針語義。這意味着如果在C++中複製迭代器,並且「碰撞」它多次 - 原始迭代器將不會被改變(儘管如果它是單程範圍,但它不是重點)可以失效。

但是,有時您確實想要從單程範圍累積數值並多次查看它們。在這種情況下,最常見的解決方案是通過人工明確地將值累積到某個容器。例如:

vector<int> cache(first,last); 

然而,三通式包裝仍然是可能在C++中,這裏是證明了概念。用法是:

auto forward_range = tee_range(first,last); 

tee_range需要單程範圍作爲參數,並返回前進範圍(這是多遍)(也有make_tee_iterator,其在迭代器級作品)。所以,你可以採取一系列的副本,並重復了好幾遍:

auto r = forward_range; 
auto out = ostream_iterator<int>(cout," "); 
copy(forward_range,out); 
copy(forward_range,out); 
copy(r,out); 

Therer也improvenment在itertools.tee - 內部,只有一個雙端隊列用於緩存值。

live demo

#include <boost/range/adaptor/transformed.hpp> 
#include <boost/iterator/iterator_facade.hpp> 
#include <boost/smart_ptr/make_shared.hpp> 
#include <boost/range/iterator_range.hpp> 
#include <boost/smart_ptr/shared_ptr.hpp> 
#include <boost/container/vector.hpp> 
#include <boost/container/deque.hpp> 
#include <boost/range/algorithm.hpp> 
#include <algorithm> 
#include <iterator> 
#include <cassert> 
#include <limits> 

template<typename InputIterator> 
class tee_iterator : public boost::iterator_facade 
    < 
     tee_iterator<InputIterator>, 
     const typename std::iterator_traits<InputIterator>::value_type, 
     boost::forward_traversal_tag 
    > 
{ 
    typedef typename std::iterator_traits<InputIterator>::value_type Value; 
    typedef unsigned Index; 
    struct Data 
    { 
     boost::container::deque<Value> values; 
     boost::container::vector<tee_iterator*> iterators; 
     InputIterator current,end; 
     Index min_index, current_index; 
     Index poped_from_front; 
     // 
     Data(InputIterator first,InputIterator last) 
      : current(first), end(last), min_index(0), current_index(0), poped_from_front(0) 
     {} 
     ~Data() 
     { 
      assert(iterators.empty()); 
     } 
    }; 
    boost::shared_ptr<Data> shared_data; 
    Index index; 
    static Index get_index(tee_iterator *p) 
    { 
     return p->index; 
    } 
public: 
    tee_iterator() 
     : index(std::numeric_limits<Index>::max()) 
    {} 
    tee_iterator(InputIterator first,InputIterator last) 
     : shared_data(boost::make_shared<Data>(first,last)), index(0) 
    { 
     shared_data->iterators.push_back(this); 
    } 
    tee_iterator(const tee_iterator &x) 
     : shared_data(x.shared_data), index(x.index) 
    { 
     if(shared_data) 
      shared_data->iterators.push_back(this); 
    } 
    friend void swap(tee_iterator &l,tee_iterator &r) 
    { 
     using std::swap; 
     *boost::find(l.shared_data->iterators,&l) = &r; 
     *boost::find(r.shared_data->iterators,&r) = &l; 
     swap(l.shared_data,r.shared_data); 
     swap(l.index,r.index); 
    } 
    tee_iterator &operator=(tee_iterator x) 
    { 
     swap(x,*this); 
    } 
    ~tee_iterator() 
    { 
     if(shared_data) 
     { 
      erase_from_iterators(); 
      if(!shared_data->iterators.empty()) 
      { 
       using boost::adaptors::transformed; 
       shared_data->min_index = *boost::min_element(shared_data->iterators | transformed(&get_index)); 
       Index to_pop = shared_data->min_index - shared_data->poped_from_front; 
       if(to_pop>0) 
       { 
        shared_data->values.erase(shared_data->values.begin(), shared_data->values.begin()+to_pop); 
        shared_data->poped_from_front += to_pop; 
       } 
      } 
     } 
    } 
private: 
    friend class boost::iterator_core_access; 
    void erase_from_iterators() 
    { 
     shared_data->iterators.erase(boost::find(shared_data->iterators,this)); 
    } 
    bool last_min_index() const 
    { 
     return boost::count 
     (
      shared_data->iterators | boost::adaptors::transformed(&get_index), 
      shared_data->min_index 
     )==1; 
    } 
    Index obtained() const 
    { 
     return Index(shared_data->poped_from_front + shared_data->values.size()); 
    } 
    void increment() 
    { 
     if((shared_data->min_index == index) && last_min_index()) 
     { 
      shared_data->values.pop_front(); 
      ++shared_data->min_index; 
      ++shared_data->poped_from_front; 
     } 
     ++index; 
     if(obtained() <= index) 
     { 
      ++shared_data->current; 
      if(shared_data->current != shared_data->end) 
      { 
       shared_data->values.push_back(*shared_data->current); 
      } 
      else 
      { 
       erase_from_iterators(); 
       index=std::numeric_limits<Index>::max(); 
       shared_data.reset(); 
      } 
     } 
    } 
    bool equal(const tee_iterator& other) const 
    { 
     return (shared_data.get()==other.shared_data.get()) && (index == other.index); 
    } 
    const Value &dereference() const 
    { 
     if((index==0) && (obtained() <= index)) 
     { 
      shared_data->values.push_back(*(shared_data->current)); 
     } 
     assert((index-shared_data->poped_from_front) < shared_data->values.size()); 
     return shared_data->values[index-shared_data->poped_from_front]; 
    } 
}; 

template<typename InputIterator> 
tee_iterator<InputIterator> make_tee_iterator(InputIterator first,InputIterator last) 
{ 
    return tee_iterator<InputIterator>(first,last); 
} 

template<typename InputIterator> 
boost::iterator_range< tee_iterator<InputIterator> > tee_range(InputIterator first,InputIterator last) 
{ 
    return boost::iterator_range< tee_iterator<InputIterator> > 
    (
     tee_iterator<InputIterator>(first,last), 
     tee_iterator<InputIterator>() 
    ); 
} 
// _______________________________________________________ // 

#include <iostream> 
#include <ostream> 
#include <sstream> 

int main() 
{ 
    using namespace std; 
    stringstream ss; 
    ss << "1 2 3 4 5"; 
    istream_iterator<int> first(ss /*cin*/),last; 
    typedef boost::iterator_range< tee_iterator< istream_iterator<int> > > Range; // C++98 
    Range r1 = tee_range(first,last); 
    Range r2 = r1, r3 = r1; 
    boost::copy(r1,ostream_iterator<int>(cout," ")); 
    cout << endl; 
    boost::copy(r2,ostream_iterator<int>(cout," ")); 
    cout << endl; 
    boost::copy(r2,ostream_iterator<int>(cout," ")); 
} 

輸出是:

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

Boost.Spirit具有Multi Pass iterator具有類似目的。

multi_pass迭代器會將任何輸入迭代器轉換爲適用於Spirit.Qi的前向迭代器。 multi_pass將在需要時緩衝數據,並在不再需要其內容時丟棄緩衝區。如果只存在迭代器的一個副本或者不能發生回溯,則會發生這種情況。