简体   繁体   中英

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; ?

Conceptually, when writing to a range, you'd want to move to the next element after writing to one. For most iterators, like eg 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, ie 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; } 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM