Thread: Iterator quandary

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277

    Iterator quandary

    I am trying to implement a reasonable iterator interface, but the STL has me a little confused. Let's say we have defined the following (somewhat nonsensical) function:

    Code:
    #include <cstdlib>
    
    template <typename ForwardIterator>
    ForwardIterator write_char(int ch, std::size_t count, ForwardIterator next, ForwardIterator eof) {
      while (count--) {
        if (next == eof)
          return ForwardIterator();
        *next++ = ch;
      }
      return next;
    }

    The iteration policy seems pretty reasonable to me. Compare with operator ==, dereference once, and return the updated position. In the case where iterator "hits the wall", return a default-initialized instance of the iterator type.

    Then we invoke it like this:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
      char buf[5] = {0};
      char* end = buf + sizeof(buf);
      char* pos = write_char('1', 3, buf, end);
      cout << "buf: '" << buf << "' (" << (pos - buf) << " chars written)" << endl;
      char* uho = write_char('!', 3, pos, end);
      if (uho == NULL)
        cout << "Error: buffer is full!" << endl;
    }
    So far, so good...or so I thought. Let's try it with "std::back_inserter":

    Code:
    #include <iostream>
    #include <string>
    #include <iterator>
    
    using namespace std;
    
    int main() {
      string buf;
      auto pos = write_char('?', 3, back_inserter(buf), back_inserter());
    }
    Well that doesn't compile. There is no default constructor for "back_inserter" and you can't even compare them with each other either. I am obviously using the wrong STL object here. But what to use? Surely there is a way to put this all together into a generic interface?
    Last edited by Sir Galahad; 08-13-2023 at 08:58 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. std::iterator::pointer and std::iterator::reference
    By etrusks in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2016, 11:27 AM
  2. Replies: 19
    Last Post: 01-06-2012, 03:01 PM
  3. Connecting input iterator to output iterator
    By QuestionC in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2007, 02:18 AM
  4. std::map::iterator
    By Magos in forum C++ Programming
    Replies: 2
    Last Post: 02-03-2006, 07:47 PM
  5. Hmm. A Quandary. Rounding/adding problem
    By Sennet in forum C++ Programming
    Replies: 11
    Last Post: 10-08-2005, 12:29 AM

Tags for this Thread