function template
<valarray>

std::abs

template<class T> valarray<T> abs (const valarray<T>& x);
Compute absolute value of valarray elements
Returns a valarray containing the absolute values of all the elements of x, in the same order.

The function calls abs (unqualified) for each element.

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

Parameters

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

Return value

A valarray object with the absolute values of the elements of x.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// abs valarray example
#include <iostream>     // std::cout
#include <cstddef>      // std::size_t
#include <cstdlib>      // std::abs(int)
#include <valarray>     // std::valarray, std::abs(valarray)

int main ()
{
  int val[] = {5, 3, -10, 4, -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;
}

Output:

foo: 5 3 -10 4 -7
bar: 5 3 10 4 7


See also