Javatpoint Logo
Javatpoint Logo

std::unary_negate() in C++

The std::unary_negate() is a wrapper function object. It returns the opposite of the unary condition it contains. A wrapper function is a procedure in a software library or computer program that is designed to invoke a second subroutine or a system call with little or no extra processing. The function std::not1() is commonly used to create objects of type unary_negate.

Header Text:

Syntax:

It has the following syntax:

Parameters: The method std::unary_negate() takes a predicate function object as an input and returns the logical counterpart of the result produced by invoking the predicate function.

Return Value: When the predicate function is called, it returns the logical complement of the result.

The following code displays the method std::unary_negate():

Filename: UnaryNegate.cpp

Output:

5

Explanation:

The given array contains numbers from 1 to 10. From the array, the numbers that are greater than or equal to 6 are 6,7,8,9,10, so the count is 5.

Example 2:

Output:

There were 1 element, which was even!

Explanation:

The program constructs an IsOdd_cla structure that serves as a functor (a function object). It provides the operator() method, which determines if a given integer is odd (x1% 2 == 1). This predicate is used to distinguish between odd and even integers.

The unary_negate function is used to generate a new predicate, which is the inverse of the IsOdd_obj predicate. It serves the purpose of finding even integers by skipping the check for odd numbers.

Advantages of the Unary_negate():

There are several advantages of the unary_negate in C++. Some main advantages of the unary_negate function in C++ are as follows:

  1. Code readability: It improves code readability and simplicity by creating the negation of a unary predicate. It eliminates the need to create a separate function for negation directly, making the code more concise and clear.
  2. Redundant Functor Definitions Should Be Avoided: Instead of establishing a new or changing an existing functor to represent a negation, std::unary_negate generates a negated version automatically on the run, avoiding the need for additional code.
  3. Algorithm Usage Simplicity: It combines smoothly with algorithms such as std::count_if, std::remove_if, and others, allowing for the use of negated predicates within these algorithms without the need to create additional function classes.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA