开发者

In what situation should ostream_iterator increment be used?

开发者 https://www.devze.com 2023-02-04 18:33 出处:网络
std::istream_iterator<std::string> ist(std::cin); std::istream_iterator<std::string> eof; std::vector<std::string> str_vec(ist, eof);
std::istream_iterator<std::string> ist(std::cin);
std::istream_iterator<std::string> eof;
std::vector<std::string> str_vec(ist, eof);
std::ofstream ofs("a");
if (!ofs) {
    throw std::runtime_error("Open file failed.");
}
std::ostream_iterator<std::string> ost(ofs, "\n");
for (size_t index = 0; index != str_vec.size(); ++index) {
    //*ost = str_vec[index];
    *ost++ = str_vec[index];
}

I got the same result no matter I use *ost++ or not. I know the meaning of istream_itera开发者_Go百科tor increment. But in what situation should ostream_iterator increment be used?

Thanks!


Further experimentation might show that you don't even need to dereference the iterator to make it work. :)

ost = str_vec[index];

All these no-op methods are necessary to give stream iterators a similar interface to other iterators.

Instead of a manual loop, you could rather use the std::copy algorithm. (As that's pretty much all an ostream_iterator is good for, this sort-of answers your question: you don't need to mess with those iterators in your own code at all!)

 std::copy(str_vec.begin(), str_vec.end(), std::ostream_iterator<std::string>(ofs, "\n"));

Considering how the copy function template is written, it might become clear where the increments and dereferencing is needed:

template <class InIter, class OutIter>
void copy(InIter begin, InIter end, OutIter result)
{
    for (InIter it = begin; it != end; ++it)
        *result++ = *it;  // <-- here, result might be almost any kind of iterator
} 


The increment operator is very likely a no-op for ostream_iterator, but it has to provide the operator to meet the requirements of output iterators. For example, a pointer is a valid output iterator and that must be incremented.


Your algorithm shouldn't be incrementing "an ostream iterator". It should be incrementing an output iterator. So, always increment your output iterator if you want to output a subsequent element. This way your algorithm will support a std::ostream_iterator as well as a std::vector<T>::iterator and a T* pointer. A std::ostream_iterator increment is likely to be a no-op, but it's not necessarily the case with other output iterators.

0

精彩评论

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

关注公众号