[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Algorithms Up: The Standard Library Previous: bitset

valarray

valarrays are designed for doing fast vector calculations. They can be initialised in various ways

// v1 is a vector of 2000 integer elements each initialised to 7
valarray<int> v1(7,2000); 

// v2 is initialised to the first 4 elements of d
const double d[]= {1.0, 1.0, 2.0, 3.0, 5.0};
valarray<double> v2(d,4);

// v3 is a copy of v2
valarray<double> v3=v2;

Operations include

v2 = 5;           // sets each element to 5
v3 *= .5;         // halve each element
v2 = v3.shift(2); // copy the elements of v3 shifted 2 to the left, into v2
                  // filling spaces with 0.0
v3 = v2.cshift(-2) //copy the elements of v2 shifted 2 to the right, into v3
                  // filling the spaces with elements that have fallen off
                  // the other end
v2= v2*cos(v3);

A slice is what you get when you take every nth element of a valarray. This is especially useful if the valarray represents the values in a 2D array - slices are the rows or columns. A slice needs to know the index of the first element, the number of elements and the 'stride' - the step-size.

slice_array<double>& v_even= v2[slice(0,v2.size()/2,2);
slice_array<double>& v_odd= v2[slice(1,v2.size()/2,2);
v_odd *=2 ; // double each odd element of v2

A gslice lets you extract subarrays from a valarray that represent the values in a 2D array.

A mask array lets you pick out arbitrary elements. It needs to contain bool values and shouldn't be bigger than the valarray it's used with. When used as a subscript, the valarray elements corresponding to the true elements of the mask array will be chosen.

bool b[]= { true, false, true, true};
valarray<bool>mask(b,4);
valarray<double>v4= v[mask];

There's also an indirect array.

valarrays are built for speed - they aren't intended to grow, and operations aren't error-checked - if you multiply together 2 valarrays of different lengths the behaviour is undefined.


next up previous contents
Next: Algorithms Up: The Standard Library Previous: bitset
Tim Love
2001-07-05