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)?
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.
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.
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.
Another option — Boost.Lambda.
for_each(v.begin(), v.end(), cout << boost::lambda::_1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With