gslice_array class template — Helper class for generalized slices
template <typename T> class gslice_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&); ~gslice_array( ); private: gslice_array( ); gslice_array(const gslice_array&); gslice_array& operator=(const gslice_array&); };
The gslice_array
class
template represents a subset of the elements of a valarray
, called a generalized slice. To
create a generalized slice, use valarray
's operator[]
with an argument of type
gslice
.
For some operations, the gslice_array
object is transparent. In
particular, you can assign a valarray
to a gslice_array
object (provided they have
the same size), or you can construct a new valarray
from a gslice_array
.
If you want to perform other operations, such as
non-assignment arithmetic, you must explicitly convert the gslice_array
to valarray
, as demonstrated in Example 13-43.
Example 13-43. Using gslice_array
// SeeExample 13-41 for the va function. int main( ) { using namespace std; const int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; valarray<int> a(data, sizeof(data)/sizeof(data[0])); cout << a << '\n'; // Prints { 1 2 3 4 5 6 7 8 } cout << a[gslice(1, va(2, 2), va(4, 2))] << '\n' << a[gslice(0, va(2, 2), va(4, 2))] << '\n'; // prints: // { 2 4 6 8 } // { 1 3 5 7 } // operator+ is not defined for gslice_array, so cast to valarray to perform // addition. cout << static_cast<valarray<int> >(a[gslice(1, va(2,2), va(4,2))]) + static_cast<valarray<int> >(a[gslice(0, va(2,2), va(4,2))]) << '\n'; // Prints: { 3 7 11 15 } // Simple assignment does not require casting. a[gslice(0, va(2, 2), va(4, 2))] = 0; cout << a << '\n'; // Prints: { 0 2 0 4 0 6 0 8 } // Computational assignment does not require casting. valarray<int> ten(10, 4); a[gslice(1, va(2, 2), va(4, 2))] *= ten; cout << a << '\n'; // Prints: { 0 20 0 40 0 60 0 80 } }
The members of gslice_array
are straightforward. When using any of the assignment operators, the
valarray
on the righthand side
must be the same size as the gslice_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
gslice_array
so it can be used
only as a return value from valarray
's operator[]
.