I wanted to use the lamda function somehow, but it doesn't work and I dont know why.
vector<int> v;
/* ... */
int median = [](vector <int> a)
{
sort(a.begin(), a.end());
return a[a.size() / 2];
}
So I created lamda function, but how can I call it? int median = [](vector<int> a) { ... } (v)
? But it doesnt work too. I have seen lamda functions only in some examples like making custom comparator. Can I make it work in my case somehow?
CodePudding user response:
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];
}(v);
//^^ --> 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
.
From cppreference.com
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.
CodePudding user response:
'median' is a function but you can declare the return type like so.
#include<functional>
vector<int> v;
/* ... */
std::function<int(vector<int>)> median = [](vector<int> a)->int
{
sort(a.begin(), a.end());
return a[a.size() / 2];
};