#ifndef cycle_facade_H #define cycle_facade_H #include #include namespace boost { template class cycle_facade : public boost::iterator_facade, typename std::iterator_traits::value_type, boost::random_access_traversal_tag > { public: typedef typename boost::iterator_facade, typename std::iterator_traits::value_type, boost::random_access_traversal_tag > super_t; typedef typename super_t::difference_type difference_type; typedef typename super_t::value_type value_type; typedef typename super_t::reference reference; explicit cycle_facade (BaseIterator _base, BaseIterator const& _b, BaseIterator const& _e) : base(_b), size (_e-_b), position ((_base - _b + size) % size) {} int index() const { int x = position % size; if (x >= 0) return x; else return x + size; } private: friend class boost::iterator_core_access; void increment () { ++position; position %= size; // prevent overflow } void decrement () { --position; position %= size; // prevent overflow } void advance (difference_type n) { position += n; position %= size; // prevent overflow } difference_type distance_to (cycle_facade const& y) const { if (size == 0) return 0; else return -(((base + position) - (y.base + y.position) + size) % size); // guess } bool equal (cycle_facade const& y) const { return distance_to (y) == 0; } reference dereference() const { return *(base + index()); } public: reference operator[] (int n) { return *(base + index()); } const reference operator[] (int n) const { return *(base + index()); } private: const difference_type size; difference_type position; BaseIterator base; }; template cycle_facade make_cycle_facade(BaseIterator current, BaseIterator b, BaseIterator e) { return cycle_facade (current, b, e); } } //namespace boost #endif