std::unary_negate() in C++ with Examples
The std::unary_negate() is a wrapper function object returning the complement of the unary predicate it holds. A wrapper function is a subroutine in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation. An object of type unary_negate are generally constructed using function std::not1().
Header File:
#include <functional>
Syntax:
std::unary_negate<class T>
variable_name(Object of class T);
Parameters: The function std::unary_negate() accepts the predicate function object as a parameters and returns the logical complement of the result generated by calling predicate function.
Return Value: It returns the logical complement of the result by calling predicate function.
Below is the program to illustrate the function std::unary_negate():
Program 1:
CPP
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
struct gfg : unary_function< int , bool > {
bool operator()( int i)
const
{
return i < 4;
}
};
int main()
{
vector< int > arr;
for ( int i = 1; i <= 10; ++i) {
arr.push_back(i);
}
unary_negate<gfg> func((gfg()));
cout << count_if(arr.begin(),
arr.end(), func);
return 0;
}
|
Explanation: In the above program array arr[] has elements from 1 to 10 and the number of elements which is greater than equals to 4 is 7.
Program 2:
CPP
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
struct IsOdd_class {
bool operator()( const int & x)
const
{
return x % 2 == 1;
}
typedef int argument_type;
} IsOdd_object;
int main()
{
unary_negate<IsOdd_class>
IsEven_object(
IsOdd_object);
int arr[] = { 1, 1, 3, 9, 5 };
int cx;
cx = count_if(arr, arr + 5, IsEven_object);
cout << "There are "
<< cx
<< " elements with even values!"
<< endl;
return 0;
}
|
Output:
There are 0 elements with even values!
Reference: http://www.cplusplus.com/reference/functional/unary_negate/
Last Updated :
03 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...