gpt4 book ai didi

c++ - 如何访问lambda函数中的变量? (c++)

转载 作者:太空狗 更新时间:2023-10-29 21:10:25 25 4
gpt4 key购买 nike

我是 cpp 的新手,所以这看起来微不足道,但我想更改 lambda 函数中的局部变量 (bool done1),但它似乎没有对 varialbe 做任何事情,而且它仍然是正确的。有什么建议么?谢谢

    bool done1 = true;
bool done2 = true;
bool done3 = true;

// associates each point to the nearest center
std::thread thread_1([this](vector<Point> points,bool done) {
for(int i = 0; i < total_points/3; i++) {
int id_old_cluster = points[i].getCluster();
int id_nearest_center = getIDNearestCenter(points[i]);
if (id_old_cluster != id_nearest_center) {
if (id_old_cluster != -1){
clusters[id_old_cluster].removePoint(points[i].getID());
}
points[i].setCluster(id_nearest_center);
clusters[id_nearest_center].addPoint(points[i]);
done = false;
}
}
},points, done1);

最佳答案

如果你想在你的线程中改变done1,lambda应该引用bool,并且done1必须被包裹进 reference_wrapper 当线程构造函数被调用时:

std::thread thread_1([this](vector<Point> points,bool& done) { // take by reference
for(int i = 0; i < total_points/3; i++) {
int id_old_cluster = points[i].getCluster();
//...
done = false;
}
}
},points, std::ref(done1) ); // <--- std::ref

另一种选择是通过引用捕获done1,然后lambda只接受一个参数:

[this,&done1](vector<Point> points) {
//...
done1 = true;
}, points);

你的 lambda 修改点 vector ,但现在它是复制的,所以当线程结束时传递的 vector 不受影响。您还需要通过引用传递分数:

std::thread thread_1([this](vector<Point>& points,bool& done) { // both args by ref
for(int i = 0; i < total_points/3; i++) {
int id_old_cluster = points[i].getCluster();
//...
done = false;
}
}
}, std::ref(points), std::ref(done1) ); // <--- std::ref 2x

关于c++ - 如何访问lambda函数中的变量? (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54467705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com