3

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?

MSalters
  • 173,980
  • 10
  • 155
  • 350
mmjuns
  • 177
  • 1
  • 11

2 Answers2

4

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

Sadique
  • 22,572
  • 7
  • 65
  • 91
4

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>.

Community
  • 1
  • 1
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • This isn't a standard library placeholder. This placeholder was/is used by Boost.Lambda to create lambdas before they were added to the language in C++11. – Simple Oct 10 '13 at 07:05
  • @Simple, true, but I didn't know the OP was using boost when I was answering:P The other answer contains links to boost docs, though. – SingerOfTheFall Oct 10 '13 at 07:36