3

I'm wondering if there's some sort of iterator that can iterate over values in a std::string, starting over from the beginning when it reaches the end. In other words, this object would iterate indefinitely, spitting out the same sequence of values over and over again.

Thanks!

Louis Thibault
  • 20,240
  • 25
  • 83
  • 152

1 Answers1

5

A generator function could be that. Boost Iterator has the iterator adaptor for that:

A sample: 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, ";"));
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • added a _short_ sample (also using `copy_n` on [LWS](http://liveworkspace.org/code/2e09ce186cca5785742f7d7b25c005d0)) – sehe Nov 07 '12 at 22:31