Mathieu Gemard
Mathieu Gemard

Reputation: 571

Dereferencing and increment with ostream_iterator

I found this code from http://en.cppreference.com/w/cpp/iterator/ostream_iterator/ostream_iterator :

#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
    std::ostream_iterator<int> i1(std::cout, ", ");
    std::fill_n(i1, 5, -1);
    std::ostream_iterator<double> i2(std::cout);
    *i2++ = 3.14;
}

Why do you need the ++ in *i2++ = 3.14;?

Upvotes: 3

Views: 303

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50063

Conceptually, when writing to a range, you'd want to move to the next element after writing to one. For most iterators, like e.g. a std::vector::iterator, that has to be done explicitly. So it kind of makes sense to include it, if only for consistency.

In the particular case of std::ostream_iterator, it does not have an actual effect though, and could be left out. You cannot overwrite an "element" of the output range anyways, advancing is implicit (and only implicit, i.e. both the increment operators as well as derefencing are no-ops in this context).

The important part is only the operator =, as explained in the relevant documentation:

#include <iostream>
#include <iterator>

int main()
{
    std::ostream_iterator<int> i1(std::cout, ", ");
    *i1++ = 1; // usual form, used by standard algorithms
    *++i1 = 2;
    i1 = 3; // neither * nor ++ are necessary
    std::ostream_iterator<double> i2(std::cout);
    i2 = 3.14;
}

Upvotes: 4

Barmar
Barmar

Reputation: 781059

The ++ operator has no effect on std::ostream_iterator. Assigning to *i2 automatically advances the output stream.

It's provided so that ostream_iterator can be used anywhere that an ordinary iterator is allowed, and most iterators have to be incremented explicitly.

Even with an ordinary iterator, it's generally only necessary to increment it if you use it multiple times. In the code snippet you found, where it's used just once, incrementing is totally unnecessary. It would be more reasonable if it were inside a loop.

Upvotes: 1

Related Questions