C++ Standard Library C++ STL Library

C++ <valarray> - abs() Function



The C++ <valarray> abs() function returns a valarray containing the absolute value of all the elements of valarray va, in the same order.

This function is overloaded in <cstdlib> abs() function for integral types, in <cmath> abs() function for floating-point types, and in <complex> abs() function for complex numbers.

Syntax

template<class T> valarray<T> abs (const valarray<T>& va);

Parameters

va Specify valarray containing elements of a type for which the function abs() is defined.

Return Value

Returns valarray containing the absolute value of all the elements of va.

Example:

The example below shows the usage of abs() function.

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

int main (){
  valarray<int> va1 = {-20, -10, 0, 10, 20};
  
  //va2 will contain absolute value
  //of all elements of va1
  valarray<int> va2 = abs(va1);
 
  cout<<"va1 contains: ";
  for(int i = 0; i < va1.size(); i++)
    cout<<va1[i]<<" ";

  cout<<"\nva2 contains: ";
  for(int i = 0; i < va2.size(); i++)
    cout<<va2[i]<<" ";   
  
  return 0;
}

The output of the above code will be:

va1 contains: -20 -10 0 10 20 
va2 contains: 20 10 0 10 20 

❮ C++ <valarray> Library