How do I use for_each to output to cout?

nakiya picture nakiya · Nov 11, 2010 · Viewed 16.1k times · Source

Is there a more straight-forward way to do this?

for_each(v_Numbers.begin(), v_Numbers.end(), bind1st(operator<<, cout));

Without an explicit for loop, if possible.

EDIT:

How to do this for std::cin with a std::vector if possible? (How to read n elements only)?

Answer

Bj&#246;rn Pollex picture Björn Pollex · Nov 11, 2010

You could achieve this using std::copy into a std::ostream_iterator:

std::vector<int> v_Numbers; // suppose this is the type
// put numbers in
std::copy(v_Numbers.begin(), v_Numbers.end(),
          std::ostream_iterator<int>(cout));

It would be even nicer if you add some suffix:

std::copy(v_Numbers.begin(), v_Numbers.end(),
          std::ostream_iterator<int>(cout, "\n"));

This assumes that your container is a vector<int>, so you will have to replace that part with the appropriate type.

Edit regarding reading input:

Conversely, you can copy from a range of std::istream_iterator into a vector using std::back_inserter:

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

If you want to read n elements only, look at this question.