Negate Function in C++ STL



The negate function in C++, is a function object (functor) that returns the negation of a the given value. In this article, we will learn how to use the negate function from the Standard Template Library (STL) in C++.

What is negate?

The negate function is a predefined function object defined in the STL that performs arithmetic negation. It takes a single value and returns its negative value. For example, if the input is 5, the output will be -5. This operation is useful when we want to apply negation inside STL algorithms like transform() or for_each() without writing a custom function.

For example, in the code below we use negate to invert a value:

#include <functional>

negate<int> neg;
int result = neg(10); // result = -10

Using negate Function in STL

The negate function is defined in the <functional> header of STL. It is a unary function object class that applies the unary minus operator. Below are some points about this function:

  • Header: <functional>
  • Syntax:
    template <class T> struct negate;
  • Parameters: One value of type T whose sign is to be reversed.
  • Return: Returns the value -x, where x is the input value.

Steps to Use negate in C++ STL

Following are steps/algorithm to use negate using C++ STL:

  • Include the <functional> header file.
  • Create an instance of negate for the required type (e.g., int).
  • Call the functor with the desired value.
  • Store or display the result.

C++ Program to Implement negate using STL

The below code is the implementation of the above algorithm in C++ language.

#include <iostream>
#include <functional>
using namespace std;

int main() {
    negate<int> neg;

    int value = 25;
    int result = neg(value);

    cout << "Original Value: " << value << endl;
    cout << "Negated Value: " << result << endl;

    return 0;
}

The output of above code will be:

Original Value: 25
Negated Value: -25

Time and Space Complexity

Time Complexity: O(1), as it performs a basic arithmetic operation.

Space Complexity: O(1), as it uses a constant amount of memory.

Updated on: 2025-05-15T11:23:14+05:30

953 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements