3

我想知道是否有某种迭代器可以迭代 std::string 中的值,当它到达结尾时从头开始。换句话说,这个对象会无限迭代,一遍又一遍地吐出相同的值序列。

谢谢!

4

1 回答 1

5

生成器函数可能就是这样。Boost Iterator 有一个迭代器适配器:

样本:http ://coliru.stacked-crooked.com/a/267279405be9289d

#include <iostream>
#include <functional>
#include <algorithm>
#include <iterator>
#include <boost/generator_iterator.hpp>

int main()
{
  const std::string data = "hello";
  auto curr = data.end();

  std::function<char()> gen = [curr,data]() mutable -> char
  { 
      if (curr==data.end())
          curr = data.begin();
      return *curr++;
  };

  auto it = boost::make_generator_iterator(gen);
  std::copy_n(it, 35, std::ostream_iterator<char>(std::cout, ";"));
}
于 2012-11-07T22:03:12.510 回答