C++ Standard Library C++ STL Library

C++ <algorithm> - find_if_not() Function



The C++ algorithm::find_if_not function returns an iterator to the first element in the range [first,last) for which the unary function pred returns false.

Syntax

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

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be considered a match if the function returns false.

Return Value

Returns an iterator pointing to the first element in the range for which pred returns false. If pred returns true for all elements in the range, the function returns last.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::find_if_not function is used to find first negative number in the given sequence.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool isPositive (int i) {
  return (i >= 0) ;
}

int main (){
  int arr[] = {10, 15, 12, -15, 14, -12};
  int * p;
  vector<int> vec = {10, 15, 12, 15, 14, 12};
  vector<int>::iterator it;

  //search for negative number in the array
  p = find_if_not(arr, arr+6, isPositive);

  //search for negative number in the vector
  it = find_if_not(vec.begin(), vec.end(), isPositive);

  //print result for array
  if(p != arr+6) {
    cout<<"Element found in the array: "<<*p<<"\n";
  }
  else {
    cout<<"Element is not found in the array.\n";
  }

  //print result for vector
  if(it != vec.end()) {
    cout<<"Element found in the vector: "<<*it<<"\n";
  }
  else {
    cout<<"Element is not found in the vector.\n";
  }

  return 0;
}

The output of the above code will be:

Element found in the array: -15
Element is not found in the vector.

❮ C++ <algorithm> Library