
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
, wherex
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.