MasterBeta
MasterBeta

Reputation: 604

In what situation should ostream_iterator increment be used?

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_iterator increment. But in what situation should ostream_iterator increment be used?

Thanks!

Upvotes: 4

Views: 428

Answers (3)

UncleBens
UncleBens

Reputation: 41331

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
} 

Upvotes: 4

wilhelmtell
wilhelmtell

Reputation: 58677

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.

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62073

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.

Upvotes: 2

Related Questions