Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to use the find_if_not() function in C++

Harsh Jain

The find_if_not() function is available in the<algorithm> library in C++. The find_if_not() function is used to return the value of the first element in the range [first, last)first element inclusive, last element exclusive. This occurs when the prediction or a parameter value is false. Otherwise, the last element of the range is given.

Syntax

The following is the function prototype:

InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);

Parameters

The find_if_not() method takes:

  • first: This is an iterator that points to the first index of the array or vector from where we want to perform the search operation.

  • last: This is an iterator that points to the last index of the array or vector from where we want to perform the search operation.

  • pred: A unary function that returns a Boolean value after checking the elements in the range.

Return value

The function returns an iterator to the first element in the range for which the pred returns false. If no such element is found, then the function returns the last element.

Code

Let’s have a look at the code.

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

bool isDivisiblyBySeven(int x){
  return x % 7;
}

int main()
{
  vector<int> a = {49,28,3,77,21,5,8};
  auto i = find_if(a.begin(), a.end(), isDivisiblyBySeven);
  cout<<"First element which is not divisible by 7 is : "<<*i;
  return 0;
}
Use find_if_not() function in C++

Explanation

  • In lines 1 to 3, we import the required header files.
  • In lines 6 to 8, we create a unary function which checks whether the number is divisible by seven.
  • In line 10, we make a main() function.
  • In line 12, we initialize a vector of int type.
  • In line 13, we use the find_if_not() function and store the result in the auto variable. The auto keyword specifies that the data type of the variable is automatically deducted from its initializer.
  • In line 14, we display the result of the find_if_not() function with a message.

This is how to use the find_if_not() function to find an iterator of the first element in the range for which the pred returns false.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring