[英]C++ How to use lambda expression to capture the previous iteration value?
我正在使用這個簡單的例子來創建一個簡單的向量,它的元素以嚴格遞增的隨機步進方式。 我有一個使用 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,
我今天剛剛學習了 lambda 表達式,並希望用更短的代碼來實現相同的實現。 我不確定是否可以在 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)) });
與上面的 class 等效的 lambda 是這樣的:
auto increment_generator = [m = 0]() mutable
{
m += 1 + (rand() % 5); //random Increment between [1,5]
return m;
};
請注意mutable
修飾符,它指示捕獲的m
不是恆定的。 默認情況下,lambda 捕獲的變量是const
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.