Open In App

negate function in C++ STL

This function is used to negate the given values i.e. to change the sign of the values. It changes the positive values to negative and vice-versa.

Note: Objects of this class can be used on standard algorithms such as transform.
Syntax:



transform(arr_begin, arr_end, arr2_begin, negate())

Parameters: It accepts four parameters which are described below:

  1. arr_begin: It is the lower bound of the given array.
  2. arr_end: It is the upper bound of the given array.
  3. arr2_begin: It is the lower bound of the second array in which the modified values to be updated.
  4. negate(): It is the function that is used to negate the values of the given array.

Return values: It returns the same values with the opposite sign.



Below is the implementation that shows the working of negate() function:




// C++ program to show the working 
// of negate() function
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
int main()
{
    int arr[] = { 5, 7, -20, -60, 50 };
  
    // using transform negation of values is done
    transform(arr, arr + 5, arr, negate<int>());
  
    for (int i = 0; i < 5; i++)
        cout << arr[i] << ' ';
  
    return 0;
}

Output:
-5 -7 20 60 -50
Article Tags :
C++