How to use the find_if_not() function in C++
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
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;}
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
inttype. - In line 13, we use the
find_if_not()function and store the result in theautovariable. Theautokeyword 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.