mmjuns
mmjuns

Reputation: 197

What does "cout <<(_1*3)" mean?

I found a simple code:

using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::for_each(
    in(std::cin), in(), std::cout << (_1 * 3) << " " );

and I found _1 is used to represent each input integer, but how does this _1 work? Anyone knows?

PS: This code is from the first example of BOOST. When I ran the file, I found the for_each will never terminate and it kept read numbers after each "return" click. Any idea why this happened?

Upvotes: 3

Views: 318

Answers (2)

Sadique
Sadique

Reputation: 22821

Lambda to multiply each number by three. After reading from stdin. in should be an iterator - paste full code please.

_1 is a placeholder as explained in the other answer. The question should have been tagged Boost as well. That is a Boost.Lambda.

Lambda expressions in details

Upvotes: 4

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

This looks like a placeholder (also look at this SO question):

The std::placeholders namespace contains the placeholder objects [_1, . . . _N] where N is an implementation defined maximum number.

When used as an argument in a std::bind expression, the placeholder objects are stored in the generated function object, and when that function object is invoked with unbound arguments, each placeholder _N is replaced by the corresponding Nth unbound argument.

The types of the placeholder objects are DefaultConstructible and CopyConstructible, their default copy/move constructors do not throw exceptions, and for any placeholder _N, the type std::is_placeholder<decltype(_N)> is defined and is derived from std::integral_constant<int, N>.

Upvotes: 4

Related Questions