C++ Valarray Library - abs Function


Advertisements

Description

It returns a valarray containing the absolute values of all the elements of x, in the same order.

Declaration

Following is the declaration for std::abs function.

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

C++11

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

Parameters

x − It is containing elements of a type for which the unary function abs is defined.

Return Value

It returns a valarray containing the absolute values of all the elements of x, in the same order.

Exceptions

Basic guarantee − if any operation performed on the elements throws an exception.

Data races

All elements effectively copied are accessed.

Example

In below example explains about std::abs function.

#include <iostream>
#include <cstddef>     
#include <cstdlib>     
#include <valarray>    

   int main () {
   int val[] = {15, 23, -1, -40, 7};
   std::valarray<int> foo (val,5);

   std::valarray<int> bar = abs (foo);

   std::cout << "foo:";
   for (std::size_t i=0; i<foo.size(); ++i)
      std::cout << ' ' << foo[i];
      std::cout << '\n';

      std::cout << "bar:";
   for (std::size_t i=0; i<bar.size(); ++i)
      std::cout << ' ' << bar[i];
   std::cout << '\n';

   return 0;
}

Let us compile and run the above program, this will produce the following result −

foo: 15 23 -1 -40 7
bar: 15 23 1 40 7
valarray.htm
Advertisements