Search code examples
c++booststlc++17

Replace for loop with std::find_if and a lambda


Consider this code:

int i{ -1 };
for(i=0; i<size; ++i) if (predicate(i)) break;
bool found{ i < size };

This should be simple to replace with std::find_if, but it needs an iterator on integers in the range of 0 to size-1. (The equivalent of C#'s IEnumerable Enumerable.Range(0, size-1).)


Solution

  • Since you tagged your question with boost tag, I assume boost::irange along with boost::find_if will do the work:

    boost::find_if(boost::irange(0, size - 1), predicate);