0

考虑以下“往返”迭代器,它尝试迭代集合中的所有元素,最终再次迭代第一个元素作为其最后一步:

#include <boost/iterator/iterator_adaptor.hpp>

template<typename IteratorBase>
class roundtrip_iterator 
     : public boost::iterator_adaptor< 
          roundtrip_iterator<IteratorBase>, // the derived class overriding iterator behavior
          IteratorBase,                     // the base class providing default behavior
          boost::use_default,               // iterator value type, will be IteratorBase::value_type
          std::forward_iterator_tag,        // iterator category
          boost::use_default                // iterator reference type
       > 
{
private:
  IteratorBase m_itBegin;
  IteratorBase m_itEnd;
  bool m_complete;

public:
  roundtrip_iterator( IteratorBase itBegin, IteratorBase itEnd ) 
    : iterator_adaptor_(itBegin), m_itBegin(itBegin), m_itEnd(itEnd), m_complete(false)
  {}

  void increment()
  { 
    if( m_complete )
    {
      base_reference() = m_itEnd;
      return;
    }

    ++base_reference();

    if(base_reference() == m_itEnd)
    {
      base_reference() = m_itBegin;
      m_complete = true;
    }
  }
};

我现在只实现了增量。

就目前而言,迭代器似乎在标准的“for”循环中运行良好,但我无法让它与 STL 算法一起使用。例如:

int main(int argc, char *argv[])
{
  std::vector<int> v;

  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  roundtrip_iterator<std::vector<int>::iterator> roundtrip(v.begin(), v.end());

  for( ; roundtrip.base() != v.end(); ++roundtrip)
    std::cout << *roundtrip << std::endl;

  std::cout << std::endl;

  roundtrip_iterator<std::vector<int>::iterator> roundtrip2(v.begin(), v.end());

  std::for_each(
    roundtrip2.base(), v.end(),
    print);

}

印刷:

1
2    
3
1 // First element printed out using standard for loop.

1
2
3 // The for_each algo stops here for some reason.

有人对两者之间的区别有任何想法吗?

4

1 回答 1

1

通过调用roundtrip2.base(),您有效地将范围传递[v.begin(), v.end)std::for_each. 您需要能够构造一个过去的值e,以便您可以传递[roundtrip2, e)

于 2012-08-18T11:03:06.020 回答