0

What does the mean [](unsigned char x)

Here is my code:

#include <algorithm>

std::string str1 = "Text with some     spaces";

str1.erase(std::remove(str1.begin(), str1.end(), ' '), str1.end());

std::cout << str1 << '\n';

std::string str2 = "Text\n with\tsome \t whitesspaces\n\n";

str2.erase(std::remove_if(str2.begin(), str2.end(), [](unsigned char x) {return std::isspace(x);}), str2.end());

std::cout << str2 <<'\n';
T Eom
  • 85
  • 1
  • 2
  • 11
  • 1
    It's lambda: https://learn.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2017 –  Mar 17 '19 at 22:24
  • It's a lambda (anonymous) function capturing nothing and taking an `unsigned char`. It forwards the argument to `std::isspace` and returns the result. – Matteo Italia Mar 17 '19 at 22:25
  • And an additional note on why the lambda would be used instead of just passing the function pointer `&std::isspace`: `isspace` takes an `int` argument, but the behavior is undefined if the value is not in the range of `unsigned char` and not the special value `EOF`. So if the type `char` is signed, most negative values are invalid to pass directly to `isspace`; the correct way to use the `` functions with `char` values is forcing a conversion `char` -> `unsigned char` (which then converts to `int`). The lambda causes an implicit conversion to do this, rather than an explicit cast. – aschepler Mar 17 '19 at 22:34

1 Answers1

0

It's the beginning of a lambda function defintion:

[](unsigned char x) {
    return std::isspace(x);
}

This defines a temporary function receiving a unsigned char and returning an int (automatically determined by the return value of std::isspace, since the lambda did not specify a return type).

paddy
  • 60,864
  • 6
  • 61
  • 103