Using streaming iterators?

I look at the ostream and istream iterators and wonder how much they are used in the real world. I looked through several books and many web pages, and all this is always a variant of the same example as

ostream_iterator<int> out_it (cout,", "); copy(myvector.begin(), myvector.end(), out_it); 

Can these stream iterators be used with real files and binary data and what is usually done?

+4
source share
3 answers

It depends. I do not find them useful, except for quick tests: input stream iterators cannot easily read only part of a file, and output iterators add a terminator rather than inserting a separator. But a lot depends; if you are working in an environment in which there are many files that are just lists of numbers, they may be appropriate; and there are cases where terms are appropriate.

+1
source

It depends. If you write something in a Unix-style filter order, they can work just fine. Otherwise, they are not so useful.

One addition that makes them much more useful (at least IME) is infix_iterator , which inserts only the specified separator between elements, and not after each. Technically, you are no longer using ostream_iterator at this point, but close enough so that most of the rest of the code does not need a difference.

+1
source

Well, the fstream family inherits from istream / ostream, so this can be done.

 ofstream outFile("myfile"); //.............. ostream_iterator<data> dataIterOut(outFile); 

The question of how common it is is more interesting. In my experience, not really. An attractive motivation would be to use standard algorithms (or some of your own decisions). But since the structure / class that you want to read / write should have all the necessary infrastructure (ctors, stream operator, etc.) Already in place, I think most people do not see the point at all. For instance.

  data d(...); *dataIterOut = d; //meh. little work saved, short on clarity 
0
source

All Articles