0

我怎样才能像这样将向量传递给异步调用?

std::vector<int> vectorofInts;
vectorofInts.push_back(1);
vectorofInts.push_back(2);
vectorofInts.push_back(3);

std::async([=]
{
    //I want to access the vector in here, how do I pass it in
    std::vector<int>::iterator position = std::find(vectorofInts.begin(), vectorofInts.end(), 2);
    //Do something 
}
4

1 回答 1

6

[=]通过指定为捕获列表,您已经在 lambda 中按值捕获它。因此,在 lambda 正文中,您可以使用vectorofInts来引用该副本。您可以指定[vectorofInts]是否要更明确;just[=]将自动捕获 lambda 使用的任何变量。

但是,您不能修改捕获的值,除非 lambda 是mutable. 因此向量被视为const,并find返回 a const_iterator。正如错误消息(发表在评论中)所说,您无法转换iteratorconst_iterator,因此将变量类型更改为std::vector<int>::iteratoror auto

如果您想访问向量本身,而不是副本,则通过指定通过引用捕获[&],或者[&vectorofInts]如果您想明确。但是,如果您在这样的线程之间共享它,请小心处理它,并确保在异步访问完成之前不要销毁它。

于 2014-11-11T12:35:40.877 回答