Search code examples
c++c++11lambdastl-algorithm

Obtaining an iterator from the element passed to a lambda when using std::find_if


I am trying to simplify a recursive function that receives an iterator. Somewhere in the function it is necessary to search for an element matching a given condition in the range going from the iterator to the end of the vector. So, I thought I could use find_if as shown below:

typedef std::vector<Foo> FooVec;
FooVec v;

int f(FooVec::iterator it) {
  /* ... */
  auto it2 = std::find_if(it, end(v),
      [](const Foo& foo) {
        auto foo_it = /* obtain the corresponding iterator for foo. */
        return f(foo_it) == 0;
      });
  /* ... */
}

But the lambda function receives an element, not an iterator to the current element, so I cannot easily call f again. I could search for foo in v in order to get the iterator, but that would be inefficient. Alternatively I could just use a regular for loop with the iterators. But I was wondering whether there is the possibility to use find_if in this situation.


Solution

  • Messy, but v.begin() + (&foo - &v.front()) is the iterator pointing to foo. Note that this only works because vector has contiguous storage: don't try it with a list or deque.