-qs9fq
Last Updated: February 25, 2016
·
1.026K
· lokiastari

C++ Learn to use stream_iterators

Try not to use explicit loops, but prefer the standard algorithms.

One easy way to practice with this is using the stream_iterators:

int main()
{
    std::vector<int>   data;

    // copy a stream of numbers from standard input to 
    // vector, then back out to the standard output.

    std::copy(std::istream_iterator<int>(std::cin),
              std::istream_iterator<int>(),
              std::,back_inserter(data)
             );

    std::copy(std::begin(data), std::end(data),
              std::ostream_iterator<int>(std::cout));
}

Header needed for the above code:

#include <vector>
#include <ostream>
#include <algorithm>
#include <iterator>

(placed here to make the code easier to read in one chunk)

2 Responses
Add your response

6187

You have a typo: extra comma before back_inserter.

I wonder what is the cost of these iterators? You're creating objects that will be copied and original ones will be destroyed (until C++11 and its move semantics).
Also some justification words would be nice to read.

over 1 year ago ·
15077

I agree with @barmaley-exe; it would be nice to see some justification of why this is worthwhile/important.

over 1 year ago ·