简体   繁体   English

C++ 如何使用 lambda 表达式来捕获之前的迭代值?

[英]C++ How to use lambda expression to capture the previous iteration value?

I'm using this simple example of creating a simple vector with its element in strictly increasing, random step manner.我正在使用这个简单的例子来创建一个简单的向量,它的元素以严格递增的随机步进方式。 I have an implementation using function objects:我有一个使用 function 对象的实现:

struct IncrementGenerator
{
    int m;
    IncrementGenerator() : m(0) {}
    int operator()()
    {
        m += 1 + (rand() % 5);     //random Increment between [1,5]
        return m;
    }
};

vector<int> myVector(10);
generate(myVector.begin()+1, myVector.end(), IncrementGenerator());

//example of the output: 0, 4, 6, 9, 10, 14, 15, 17, 20, 25,

I've just learnt lambda expression today and would like to do the same implementation in much short code.我今天刚刚学习了 lambda 表达式,并希望用更短的代码来实现相同的实现。 I'm not sure if I can capture the previous iteration in the lambda expression and add on a random number onto it:我不确定是否可以在 lambda 表达式中捕获上一次迭代并在其上添加一个随机数:

// my idea is such, but not really sure what to write in the expression so i put some question mark.
generate(myVector.begin()+1, myVector.end(),[?]()->int{return ? + (1 + (rand()%5)) });

The lambda equivalent to the class above is this:与上面的 class 等效的 lambda 是这样的:

auto increment_generator = [m = 0]() mutable
{
    m += 1 + (rand() % 5);     //random Increment between [1,5]
    return m;
};

Note the mutable modifier which indicates that the captured m is not constant.请注意mutable修饰符,它指示捕获的m不是恒定的。 By default, variables captured by lambdas are const .默认情况下,lambda 捕获的变量是const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM