Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

C++ std::valarray class

Reference for std::valarray: element-wise arithmetic on numeric arrays, sum, min, max, apply, shift, slices and masks, plus when to prefer vector instead.

std::valarray<T> (header <valarray>) is an array of numbers designed for whole-array arithmetic. Operators and math functions apply to every element at once: a + b, a * 2.0, std::sqrt(a). Compound results are compared with == by element and give a valarray<bool>.

It also offers slice, mask and indirect views for picking parts of an array. In practice valarray is rarely used in new code: std::vector with algorithms or a numeric library covers most needs. It is still handy for short numeric snippets.

C++
std::valarray<int> a{1, 2, 3};
a *= 10;               // 10 20 30
int s = a.sum();       // 60

Try it

C++ Element-wise arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Slices, masks and shift

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class T> class valarray;

valarray();                          // empty
explicit valarray(std::size_t n);    // n value-initialized elements
valarray(const T& value, std::size_t n);
valarray(std::initializer_list<T>);
Member Description
size() Number of elements.
resize(n, value) Changes the size and discards old contents, filling with value.
sum(), min(), max() Reductions. On an empty array the behavior is undefined.
apply(f) Returns a new array with f applied to each element.
shift(n), cshift(n) Shift or rotate by n positions (positive moves toward the front).
operator[](slice) Strided view. gslice takes multi-dimensional strides.
operator[](valarray<bool>) Mask view of elements where the mask is true.
operator[](valarray<size_t>) Indirect view of chosen indices.

Note on constructors: std::valarray<int> v(3, 5) means five copies of 3: the value comes first and the count second, the reverse of std::vector<int>(5, 3). Easy to mix up, and with integer element types both orders compile.

Errors / undefined behavior: an operation between arrays of different sizes is undefined, as is min(), max() or indexing past the end of an empty array.

Usage notes

  • Arrays must have equal sizes for binary operations. There is no broadcasting except with a scalar.
  • Expression templates: results may be proxy types, so auto r = a + b; can hold a lazily evaluated expression that refers to a and b. Name the type explicitly (std::valarray<double>) when you keep the result.
  • No iterators in the usual sense, but begin(v) and end(v) free functions work, so range-for and algorithms are usable.
  • Compound assignment (+=, *=, <<= and the rest) works with a scalar or another array.
  • Special math is supported through overloads of abs, sqrt, exp, log, sin, pow and so on for valarray.
  • Performance: the standard allows aliasing-free optimizations, but most vectorization today comes from the compiler on plain loops over a std::vector.