I can't understand the code below.
(from https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html)
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::for_each(
in(std::cin), in(), std::cout << (_1 * 3) << " " );
}
The web page doesn't explain anything for the code.
What I can't understand is the line with std::for_each
function.
std::for_each
is defined as below.
template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn);
So first
is in(std::cin)
, last
is just in()
, the function
is the cout
statement.
Could anyone explain to me the syntax of first
and last
syntax and meaning in the example code?
The first
iterator seems to be constructed with initial value std::cin
, but what's the use of in()
for the last value?
I also can't understand the _1
part.
The program outputs 3 *
any number of integer values I type in.
If you look at the description of the constructor of
std::istream_iterator
you can see thatin()
constructs the end-of-stream iterator.As for
in(std::cin)
:source
What this does is to replace the placeholder
_1
with every element in the iteration sequence and multiply it by 3, using the result in the output stream, as it should, given the unary function argument.source