rprospero
rprospero

Reputation: 961

Use TBB to create a vector in parallel

I have a vector<int> foo and a function float bar(int). Using the algorithms library, I can populate a vector<float> quux with

transform(foo.begin(), foo.end(), quux.begin(), bar);

My foo function happens to be very slow and I was hoping to use the TBB library to parallelise this code across multiple threads. I would have though that this would be an ideal case, since all the operations are independent. However, there doesn't seem to be a parallel_transform algorithm. Every example I've seen with the parallel_for algorithms puts the data back into the original array, which I can't do, since I'm changing the type.

Upvotes: 2

Views: 1048

Answers (1)

ypnos
ypnos

Reputation: 52337

You can use a reference to the target to make it happen. Example code:

std::vector<float> quux(foo.size());
parallel_for(size_t(0), foo.size(), [&foo,&quux] (size_t i) {
    quux[i] = bar(foo[i]);
});

Upvotes: 6

Related Questions