c++ - How can I access of a variable inside a lambda without using a global variable? -
i'm not sure, maybe can me.
how can access variable inside lambda? example:
float lim; int main() { std::cin >> lim; std::vector<float> v = {1.0f,4.5f,3.9f,0.2f,8.4f}; v.erase(std::remove_if(v.begin(),v.end(),[](float f){return f > lim}),v.end()); (auto : v) std::cout << i; return 0; } so example works, can specify value 'lim' , values in vector bigger lim remove inside vector. how can avoiding global variable lim hold value?
thanks.
use lambda with capture. notice [&].
here demo.
#include <iostream> using namespace std; int main() { int k=0;int n=0; auto func1=[=]()mutable{k=1;n=1;}; //capture k value func1(); std::cout<<k<<std::endl; //print 0 auto func2=[&](){k=2;n=1;}; //capture k reference func2(); std::cout<<k<<std::endl; //print 2 (k changed) auto func3=[k]()mutable{k=3;/* n=1; compile fail*/}; //capture k value func3(); std::cout<<k<<std::endl; //print 2 auto func4=[&k](){k=4; /* n=1; compile fail*/}; //capture k reference func4(); std::cout<<k<<std::endl; //print 4 (k changed) } more mutable : why c++0x's lambda require "mutable" keyword capture-by-value, default?
Comments
Post a Comment