P
P
pixik2016-10-11 18:15:39
C++ / C#
pixik, 2016-10-11 18:15:39

What are closures in C++ and how do you use them?

Good afternoon! I can’t understand what closures are for and why it’s better to live with them than without them? Who uses it in real projects, can you share your experience?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2016-10-11
@pixik

Closures are inseparable from lambdas. They allow you to pass references to the lambda. For example, in a lambda you needed to change a private class variable. Without a closure, you would have to make a setter and a getter (which already changes the class interface, they can be called where it would not be worth it), pass a pointer to an object into the lambda.
And so you work with an object variable inside the lambda, as if it were a local variable of the lambda.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

using IntV = vector<int>;

int main(int argc, char const *argv[]) {

  IntV v = {0, 9, 4, 6, 7, 8, 5, 6};
  size_t count = 0;

  for_each(begin(v), end(v), [](IntV::value_type x){cout << x << " ";});
  cout << endl;

  sort(begin(v), end(v), [&count /*closure*/](IntV::value_type &a, IntV::value_type &b){
    ++count;
    return a < b;
  });

  cout << count << endl;

  for_each(begin(v), end(v), [](IntV::value_type x){cout << x << " ";});
  cout << endl;

  return 0;
}

Here is an example for you to count the number of comparisons when sorting a vector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question