In my code, I have the following:
ostream_iterator<double> doubleWriter(cout, " ~ ");
// ...
*doubleWriter = 1.1;
doubleWriter++;
*doubleWriter = 2.2;
*doubleWriter = 3.3; // shouldn't 2.2 be overwritten?
doubleWriter++;
*doubleWriter = 44.2;
cout << endl << endl;
I expected it to output this:
1.1 ~ 3.3 ~ 44.2 ~
Instead, the output was this:
1.1 ~ 2.2 ~ 3.3 ~ 44.2 ~
Why does this happen? It would seem to me that I overwrite 2.2 and stick 3.3 in its spot, since I didn’t increment. Is incrementation an optional step?
For standard
ostream_iterator, operator++(both prefix and postfix) is a no-op. It does nothing and makes no difference.There’s no need to do the
++manually, since the iterator always “advances” when you output something through it.P.S. According to library Defect Report 485, the intent was to require that assignment and increments alternate. This requirement apparently haven’t made it into the current version of the standard. But in the future revisions, it will be included. In other words, as others already noted, the proper way to use output iterator is to alternate assignments and increments.