【发布时间】:2023-02-21 19:52:56
【问题描述】:
我是 c++ 的新手,我在我的一个项目中使用 lambdas。但是我的项目没有工作,因为我的变量没有在 lambda 中更新。这是一个例子:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = {1,2,3}; //declaring vector with 3 elements
auto lambda = [vec]{ //declaring the lamba
for(auto i:vec){ //looping through every item of the vector as i
cout<<i<<endl; //outputing i followed by a new line
}
};
lambda(); //outputs 1 2 and 3
vec.push_back(4); //adding 4 to the vector
lambda(); //still outputs 1 2 and 3. why isn't the 4 outputed?
}
请帮我解决这个问题。我不知道如何解决它。
【问题讨论】: