Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do you have to increment ostream_iterator when writing?

In many examples of ostream_iterator I notice that an increment operation is used between writes:

e.g.

#include <iostream>
#include <iterator>

using namespace std;

int main() {
  ostream_iterator<char> itr{ cout };
  *itr = 'H';
  ++itr; // commenting out this line appears to yield the same output
  *itr = 'i';
}

On the cpp reference increment (operator++) is listed as a no-op. Is there a reason to include it despite being a no-op? Is it a "best-practice" to include?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Why does ostream_iterator exist at all, when you can print directly to cout?

Answer: to be used with functions that expect an iterator.

There is a bunch of requirements that a type has to satisfy to be "an iterator" (and that those functions expect), and overloading ++ and * in a certain way is one of them.

Both * and ++ do nothing for an ostream iterator. If you’re asking if you should call them or not, you don’t need ostream_iterator in the first place.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading