2

What is the effect of this statement:

std::replace_if(ln.begin(),ln.end(),[=](int c){return c=='\n'||c==' ';},0);

Specifically, I'd like to know:

What's the meaning of

[=](int c){return c=='\n'||c==' ';}

Where's the grammar for this defined?

ildjarn
  • 62,044
  • 9
  • 127
  • 211

3 Answers3

2

[=](int c){return c=='\n'||c==' ';}

is a lambda expression that creates an unnamed function object. It is callable with one parameter and returns a boolean. The square brackets are the so-called "lambda introducer" which contains the so-called "capture-clause". The capture-clause tells the compiler how the lambda object captures surrounding local variables.

std::replace_if(ln.begin(),ln.end(),[=](int c){return c=='\n'||c==' ';},0);

replace_if takes two iterators for a sequence, a functor (more specifically: a predicate) and some other value. It iterates over the elements of the sequence called ln and replaces each element with 0 if the given predicate (the lambda expression) returns true for that element.

So, basically, this line of code will replace each space and line feed character in ln with a null terminator.

sellibitze
  • 27,611
  • 3
  • 75
  • 95
1

It's a lambda function. A function that has no name and is defined inline in the code. It's been added to C++ with the C++11 Standard. So, it's relatively new.

You can read about them here

jtepe
  • 3,242
  • 2
  • 24
  • 31
1

It's a lambda. It replaces the integers c in the container ln with 0 if c == '\n' or c == ' '. Since the container seems to hold characters, you can basically say it replaces spaces and newlines with null-terminating characters.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625