0

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 
}
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • What caused you to ask this? Is something specific going wrong? – doctorlove Nov 11 '14 at 12:48
  • 1
    I think change the capture to by reference `[&]` should do it for you. – Niall Nov 11 '14 at 12:54
  • @doctorlove When I use [=] the std::find gives me an error: Error 1 error C2440: 'initializing' : cannot convert from 'std::_Vector_const_iterator<_Myvec>' to 'std::_Vector_iterator<_Myvec>' – Harry Boy Nov 11 '14 at 13:10
  • 2
    @HarryBoy: That's because the vector is `const` (since the lambda isn't `mutable`), so `find` returns a `const_iterator`. Change the type of `position` to `std::vector::const_iterator` or `auto`. – Mike Seymour Nov 11 '14 at 13:45

1 Answers1

6

You're already capturing it by value in the lambda, by specifying [=] as the capture list. So, within the lambda body, you can use vectorofInts 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 as const, and find returns a const_iterator. As the error message (posted in a comment) says, you can't convert iterator to const_iterator, so change your variable type to std::vector<int>::iterator or auto.

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644