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.
Access an element in vector using operator [] element_reference operator[] (size_type n); element_reference operator[] (size_type n); element_reference operator[] (size_type n); It returns the reference of element in vector at index n.
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:
copy_if(a.begin(), a.end(), b.begin(),
[&] (const int& x) -> bool { // <-- do not forget reference here
size_t index = &x - &a[0]; // Still ugly... but simple
return mask[index];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With