Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access of a variable inside a lambda without using a global variable?

I'm not sure, but maybe you can help me.

How can I access to a variable inside a 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());
  for (auto i : v) std::cout << i;
  return 0;
}

So this example works, I can specify a value 'lim' and all values in the vector bigger than lim will remove inside the vector. But how can I do this avoiding a global variable lim to hold the value?

Thanks.

like image 732
0xf10 Avatar asked Feb 27 '26 07:02

0xf10


1 Answers

Use lambda with capture. Notice the [&].
Here is a demo.

#include <iostream>
using namespace std;

int main() {
    int k=0;int n=0;

    auto func1=[=]()mutable{k=1;n=1;};  //capture k by value
    func1();
    std::cout<<k<<std::endl;  //print 0

    auto func2=[&](){k=2;n=1;};         //capture k by reference
    func2();
    std::cout<<k<<std::endl;  //print 2  (k changed)

    auto func3=[k]()mutable{k=3;/* n=1; compile fail*/}; //capture k by value
    func3();
    std::cout<<k<<std::endl;  //print 2

    auto func4=[&k](){k=4;      /* n=1; compile fail*/}; //capture k by reference
    func4();
    std::cout<<k<<std::endl;  //print 4  (k changed)
} 

More about mutable : Why does C++0x's lambda require "mutable" keyword for capture-by-value, by default?

like image 50
javaLover Avatar answered Feb 28 '26 20:02

javaLover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!