0

I was going through techiedelight article link

I didn't get the meaning of [&m](char &c) { m[c]++; } in std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; });

#include <iostream>
#include <unordered_map>
#include <algorithm>
 
int main()
{
    std::unordered_map<char, int> m;
 
    std::string s("abcba");
    std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; });
 
    char ch = 's';
 
    if (m.find(ch) != m.end()) {
        std::cout << "Key found";
    }
    else {
        std::cout << "Key not found";
    }
 
    return 0;
}

Someone please explain how it is working. Thanks in advance.

  • [`std::for_each`](https://en.cppreference.com/w/cpp/algorithm/for_each), [lambdas](https://en.cppreference.com/w/cpp/language/lambda), and [`std::map`](https://en.cppreference.com/w/cpp/container/map). – sweenish Oct 07 '21 at 14:28

1 Answers1

1
[&m](char &c) { m[c]++; }

this is a lambda. A lambda is an anonymously typed function object using shorthand.

It is shorthand for roughly:

struct anonymous_unique_secret_type_name {
  std::unordered_map<char, int>& m;
  void operator()(char& c)const {
    m[c]++;
  }
};
std::for_each(s.begin(), s.end(), anonymous_unique_secret_type_name{m} );

the [&m](char &c) { m[c]++; } both creates the type and constructs an instance. It captures (by reference) the variable m, which it exposes as m within its body.

As a function-like object (aka a function object), it has an operator() that can be called like a function. Here this operator() takes a char& and returns void.

So for_each calls this function object on each element of the ranged passed (in this case, the string).

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • ...and does what to the map? Seems like you'd want that piece to fully explain the line. – sweenish Oct 07 '21 at 14:47
  • @sweenish I assumed it was the lambda syntax that confused the OP. I mean, I could also explain what `int main` means. – Yakk - Adam Nevraumont Oct 07 '21 at 18:04
  • It's probably a good assumption, but they asked about the line of code. For completeness, I recommended finishing the explanation of the line. No need to condescend. – sweenish Oct 07 '21 at 18:35