How can I pass in a vector to an async call like so??
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
}
You're already capturing it by value in the lambda, by specifying
[=]
as the capture list. So, within the lambda body, you can usevectorofInts
to refer to that copy. You could specify[vectorofInts]
if you want to be more explicit; just[=]
will automatically capture any variable that's used by the lambda.However, you can't modify captured values unless the lambda is
mutable
. So the vector is treated asconst
, andfind
returns aconst_iterator
. As the error message (posted in a comment) says, you can't convertiterator
toconst_iterator
, so change your variable type tostd::vector<int>::iterator
orauto
.If you want to access the vector itself, not a copy, then capture by reference by specifying
[&]
, or[&vectorofInts]
if you want to be explicit. But be careful what you do with it if you share it between threads like that, and make sure you don't destroy it until the asyncronous access has completed.