nakiya nakiya - 1 year ago 77
C++ Question

How do I use for_each to output to cout?

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

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

Without an explicit
loop, if possible.


How to do this for
with a
if possible? (How to read
elements only)?

Answer Source

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(),

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>(),

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download