title: C++ custom lazy iterator
body: <p>I have a somewhat simple text file parser. The text I parse is split into blocks denoted by <code>{ block data }</code>.</p>
  
  <p>My parser has a <code>string read()</code> function, which gets tokens back, such that in the example above the first token is <code>{</code> followed by <code>block</code> followed by <code>data</code> followed by <code>}</code>.</p>
  
  <p>To make things less repetitive, I want to write a generator-like iterator that will allow me to write something similar to this JavaScript code:</p>
  
  <pre><code>* readBlock() {
      this.read(); // {
  
      let token = this.read();
  
      while (token !== '}') {
          yield token;
  
          token = this.read();
      }
  }
  </code></pre>
  
  <p>which in turn allows me to use simple for-of syntax:</p>
  
  <pre><code>for (let token of parser.readBlock()) {
      // block
      // data
  }
  </code></pre>
  
  <p>For C++ I would like something similar:</p>
  
  <pre><code>for (string token : reader.read_block())
  {
      // block
      // data
  }
  </code></pre>
  
  <p>I googled around to see if this can be done with an iterator, but I couldn't figure if I can have a lazy iterator like this which has no defined beginning or end. That is, its beginning is the current position of the reader (an integer offset into a vector of characters), and its end is when the token <code>}</code> is found.
  I don't need to construct arbitrary iterators, or to iterate in reverse, or to see if two iterators are equal, since it's purely to make linear iteration less repetitive.</p>
  
  <p>Currently every time I want to read a block, I need to re-write the following:</p>
  
  <pre><code>stream.skip(); // {
  while ((token = stream.read()) != "}")
  {
      // block
      // data
  }
  </code></pre>
  
  <p>This becomes very messy, especially when I have blocks inside blocks. To support blocks inside blocks, the iterators would have to all reference the same reader's offset, such that an inner block will advance the offset, and the outer block will re-start iterating (after the inner is finished) from that advanced offset.</p>
  
  <p>Is this possible to achieve in C++?</p>