Std::find_if question


function template
<algorithm>
std::find_if

template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

Find element in range
Returns an iterator to the first element in the range [first,last) for which pred returns true. If no such element is found, the function returns last.

--------------------------------------------------

Above are the texts about "find_if" function from C++ library. I am wondering how can I distinguish if the last element is returned because of satisfaction by "pred", or because of "no such element is found".

Thanks,
L


I am wondering how can I distinguish if the last element is returned because of satisfaction by "pred", or because of "no such element is found".

All STL algorithms work with iterators where begin points to the first element and end points one past the end (whatever that means). So for find, you need to compare the returned iterator against end to check if the search was successful.
OK. I see. I need to make an additional check for the last element.

Thanks,
L
landlord1984 wrote:
I need to make an additional check for the last element.

No you shouldn't need an additional check. As kbw mentioned standard containers end function returns an iterator pointing to one past the last element in the container, so passing begin() and end() to find_if will check the entire container.
1
2
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

I am wondering how can I distinguish if the last element is returned because of satisfaction by "pred", or because of "no such element is found".

There is no need to distinguish, because the last is never "satisfaction". The 'last' is "one past the last element that is operated on".

Similarly
1
2
3
for ( auto x = first; x < last; ++x ) {
  assert( x < last );
}


Therefore,
1
2
3
4
5
6
auto result = std::find_if( foo, bar, gaz );
if ( bar != result ) {
  // satisfaction is at result
} else {
  // gaz was not true in range [foo..bar[
}


Or, to find every occurrence:
1
2
3
4
5
6
7
auto result = std::find_if( foo, bar, gaz );
while ( bar != result ) {
  // satisfaction is at result

  // find next
  result = std::find_if( result+1, bar, gaz );
}

Topic archived. No new replies allowed.