lambda expression problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>

int main(){

    std::vector<double> vec(100);
    //...initialize it

    double sum= [&vec]{       
	double sum{ 0 }; 
	for (auto x : vec)
	    sum += x;
	return sum;
    };

}


I'm getting compiler error
no suitable conversion function from "lambda []double()->double" to "double" exists


I dont really understand this conversion problem. Even this isnt working and is giving me the same error
double random_number = []{ return double{ 2 }; };

What exactly am I missing? Any help appreciated!
Last edited on
"[]{ return double{ 2 }; }" is a function object, you can't store that into a variable of type double.

If you want to call the function, you need to use the function call operator():
 
double random_number = []{ return 2.0; }();
Tnx a lot for answer man!

Its weird that () is after body not before it.

Both codes actually work even if i dont change them just put () after lambdas body.

When I read Stroustrups book he said that i dont even have to use parentheses if lambda doesnt take any arguments so the shortest lambda would be []{}, now turns out its []{}()?
the function call operator () always appears after the function: rand(), getchar(), []{ return 2.0; }()

[]{} is the shortest lambda expression.
If executed, it results in a nameless function that may be stored in a varable or called right away:
1
2
3
auto f = []{}; // create and store
f(); // call the stored lambda
[]{}(); //  create and call right away 
Last edited on
Ohh, thank you very much man, very appreciated :)
Topic archived. No new replies allowed.