<valarray>

The <valarray> header declares types and functions for operating on arrays of numerical values. The intention is to provide types that could be optimized on certain hardware platforms for computationally-intensive programs. The consensus in the C++ user community seems to be that the standard failed to live up to the intentions. Several other numerical libraries, such as Blitz++ and MTL, provide high-performance matrix solutions. (See Appendix B for more information about Blitz++.) Most programs do not need <valarray>.

A valarray is a class template that represents a one-dimensional array of numerical values. The array can grow at runtime. All the arithmetic operators and mathematical functions are overloaded to work with two valarray arguments or with a valarray and a scalar. You can also work with parts of an array: slices, generalized slices, masks, and indirect arrays.

A slice is a set of elements of a valarray, with a starting index, a count, and a stride (an index interval). A generalized slice (gslice) lets the stride count and length vary, which can be used to implement multidimensional arrays. A mask is a valarray of flags, in which the flags indicate whether the corresponding item is part of the masked array. An indirect array is an array of indices. Each of these concepts is explained in this section.

The most important distinguishing feature of valarrays is that they do not allow aliasing, that is, an object cannot be an element of more than one valarray. This enables additional optimizations that are not possible on ordinary arrays.

Because valarray is optimized for performance, no error-checking is performed. Referring to an index out of range or operating on arrays of different size result in undefined behavior—the same as with ordinary arrays. Unlike ordinary arrays, a convenient size( ) member function helps to ensure that you do not make mistakes.

See the <cmath> header for scalar mathematical functions and <numeric> for a few numeric algorithms. See <complex> for complex numbers.

Throughout this section, examples show valarray objects and subsets printed using operator<<, which is shown in Example 13-40.

Example 13-40. Printing a valarray or subset array

// Print a valarray on one line, enclosed by curly braces. For example: 
// "{ 1 2 3 }".
template<typename T>
void print_valarray(std::ostream& out, const std::valarray<T>& a)
{
  out << '{';
  for (size_t i = 0; i < a.size(  ); ++i)
    out << ' ' << a[i];
  out << " }";
}
   
// Print a slice_array, gslice_array, etc. by converting to a valarray.
// Converting a valarray to a valarray is wasteful, but harmless for these simple
// examples.
template<template<typename T> class U, typename T>
std::ostream& operator<<(std::ostream& out, const U<T>& x)
{
  print_valarray(out, static_cast<std::valarray<T> >(x));
  return out;
}