Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 for loop, if possible.

EDIT:

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

like image 322
nakiya Avatar asked Nov 11 '10 09:11

nakiya


People also ask

Which is the correct syntax of For_each () *?

Syntax: for_each (InputIterator start_iter, InputIterator last_iter, Function fnc) start_iter : The beginning position from where function operations has to be executed. last_iter : The ending position till where function has to be executed.

What is std :: For_each?

std::for_each is an STL algorithm that takes a collection of elements (in the form of a begin and end iterator) and a function (or function object), and applies the function on each element of the collection. It has been there since C++98.


2 Answers

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.

like image 52
Björn Pollex Avatar answered Sep 20 '22 03:09

Björn Pollex


Another option — Boost.Lambda.

for_each(v.begin(), v.end(), cout << boost::lambda::_1);
like image 45
Cat Plus Plus Avatar answered Sep 19 '22 03:09

Cat Plus Plus