Declaring lambda with int type not working [closed]

Can I make it work in my case somehow?

Yes you can. You can either call it immediately after the definition:

int median = [](std::vector<int> a) {
    std::sort(a.begin(), a.end());
    return a[a.size() / 2];   
//^^  --> invoke immediately with argument

See for reference: How to immediately invoke a C++ lambda?

or define the lambda and call it later.

/* const */ auto median = [](std::vector<int> a) { ...}
int res = median(v);

Note that I have used auto type, to specify the type of the lambda function. This is because, lambda has so-called closure type, which we can only mention either by a auto or any type erasure mechanism such as std::function.


The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression.

Browse More Popular Posts

Leave a Comment