Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain index of element from predicate passed to some STL algorithm?

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.

like image 211
Mikhail Avatar asked Feb 28 '12 11:02

Mikhail


People also ask

How do you access the elements of a vector by index?

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.


1 Answers

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];
  });
like image 196
Mikhail Avatar answered Oct 01 '22 04:10

Mikhail