Say, I have vector of elements and a mask array, and I want to extract elements from vector with true corresponding mask value to separate vector. Is there a way to use std::copy_if for this purpose? The problem is, I only have value of element inside predicate, not iterator to it, so I cannot know the actual index to address mask array.
I can directly manipulate addresses like this:
vector<bool> mask;
vector<int> a, b;
copy_if(a.begin(), a.end(), b.begin(), [&] (int x) -> bool {
size_t index = &x - &a[0]; // Ugly...
return mask[index];
});
However, I find this to be ugly solution. Any better ideas?
Update: Another possible solution is to use external iterator on mask:
vector<bool> mask;
vector<int> a, b;
auto pMask = mask.begin();
copy_if(a.begin(), a.end(), b.begin(), [&] (int x) {
return *pMask++;
});
However, this solution requires additional variable in outer namespace which still is not desirable.
Ok, after a bit of investigation I come out with the first example be the easiest way. However, one should not forget to pass value in lambda by (const) reference for not to take address of local copy of a parameter: