Std::find_if question

Mar 31, 2016 at 4:17pm

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


Mar 31, 2016 at 4:26pm
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.
Mar 31, 2016 at 4:52pm
OK. I see. I need to make an additional check for the last element.

Thanks,
L
Apr 1, 2016 at 1:24am
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.
Apr 1, 2016 at 7:26am
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.