mask_array class template — Helper class for mask arrays
template <typename T> class mask_array { public: typedef T value_type; void operator=(const valarray<T>&) const; void operator*=(const valarray<T>&) const; void operator/=(const valarray<T>&) const; void operator%=(const valarray<T>&) const; void operator+=(const valarray<T>&) const; void operator-=(const valarray<T>&) const; void operator^=(const valarray<T>&) const; void operator&=(const valarray<T>&) const; void operator|=(const valarray<T>&) const; void operator<<=(const valarray<T>&) const; void operator>>=(const valarray<T>&) const; void operator=(const T&); ~mask_array( ); private: mask_array( ); mask_array(const mask_array&); mask_array& operator=(const mask_array&); };
The mask_array
class
template represents a subset of the elements of a valarray
. To create a mask subset, use
valarray
's operator[]
with an argument of type
valarray<bool>
. An element
is included in the result set if the corresponding element in the
argument is true
.
For some operations, the mask_array
object is transparent. In
particular, you can assign a valarray
to a mask_array
object (provided they have the
same size), or you can construct a new valarray
from a mask_array
.
If you want to perform other operations, such as
non-assignment arithmetic, you must explicitly convert the mask_array
to valarray
, as demonstrated in Example 13-45.
Example 13-45. Using mask_array
// Simple average template<typename T> T avg(const std::valarray<T>& a) { return a.sum( ) / a.size( ); } int main( ) { using namespace std; const int data[] = { 1, -3, 10, 42, -12, 13, -7, 69 }; valarray<int> a(data, sizeof(data)/sizeof(data[0])); cout << a << '\n'; // Prints: { 1 -3 10 42 -12 13 -7 69 } // Print the values that are above average. cout << "avg=" << avg(a) << '\n'; cout << a[a > avg(a)] << '\n'; // Prints: { 42 69 } // Force all negative values to be 0. Notice how no cast is needed for the // simple assignment. a[a < 0] = 0; cout << a << '\n'; // Prints: { 1 0 10 42 0 13 0 69 } // Other operations, such as multiplication by a scalar, are defined only for // valarray, so a cast is needed. cout << static_cast<valarray<int> >(a[a > 0]) * -1 << '\n'; // Prints: { -1 -10 -42 -13 -69 } }
The members of mask_array
are straightforward. When using any of the assignment operators, the
valarray
on the righthand side
must be the same size as the mask_array
on the lefthand side. You can
also assign a scalar to every element of the array. Note that the
default constructor, copy constructor, and copy assignment operator
are all private. The purpose of this is to restrict the use of
mask_array
so it can be used only
as a return value from valarray
's
operator[]
.