开发者

Usages of stream iterators?

I have been开发者_StackOverflow looking at ostream and istream iterators and wondering how much used they are in the real world. I have looked at a couple of books and a lot of web pages and everything is always a variation of the same example like

  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 is that normally done?


It depends. I don't find them all that useful, except for quick tests: the input stream iterators can't easily read just part of a file, and the output iterators append a terminator, rather than inserting a separator. But a lot depends; if you're working in an environment where there are a lot of files that are just lists of numbers, they might be appropriate; and there are cases where terminators are appropriate.


It depends. If you're writing something on the order of a Unix-style filter, they can work quite nicely. Otherwise, they're not nearly as useful.

One addition that makes them much more useful (at least IME) is an infix_iterator that only inserts the specified separator between elements instead of after every one. Technically you're no longer using an ostream_iterator at that point, but it's close enough that most of the rest of the code doesn't need to care about the difference.


Well the fstream family inherits from istream/ostream so it 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 very. The compelling motivation would be to leverage the standard algorithms (or some of your own making). But since the struct/class you want to read/write needs to have all the necessary infrastructure (ctors, stream operators, etc.) already in place I imagine most people don't otherwise see the point. E.G.

 data d(...);

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜