dimanche 25 octobre 2020

Temporary captured-variables in lambda functions - C++11

I was trying out something like this to pre-populate a map using a vector-list of strings. The code is self-explanatory:

Constructor(const vector<string>& names) {
  for_each(names.begin(), names.end(),
                     [this, counter = 1](const String& choice) mutable {
                            nameMapping.emplace(choice, counter++);
                        }
  );
)

Something I didnt really understand is how does counter work?

FYI: counter is no-where declared outside of the lambda function.

But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?

Can someone please help me understand whats going on.

Aucun commentaire:

Enregistrer un commentaire