C++: “auto” on anonymous functions

C++14 introduced an improvement to the way we can declare anonymous functions (a.k.a. lambda expressions).

For example, before C++14, if you wanted to pass an anonymous function to the sort algorithm, you had to do something like this:

int main()
{
  vector<string> s = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

  sort(s.begin(), s.end(), [](const string& a, const string& b)
  {
    return b < a; // descending order
  });

  for (auto& i : s) cout << i << "\n";
}

Since C++14, you can let the compiler to deduce the type of the variables passed as parameters (using auto) in a lambda expression, so you could rewrite the example above as follows:

int main()
{
  vector<string> s = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

  sort(s.begin(), s.end(), [](auto& a, auto& b)
  {
    return b < a; // descending order
  });

  for (auto& i : s) cout << i << "\n";
}

More info about auto.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s