slice_array class template — Helper class for slice
template <typename T> class slice_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&); ~slice_array( ); private: slice_array( ); slice_array(const slice_array&); slice_array& operator=(const slice_array&); };
The slice_array
class
template represents a subset of the elements of a valarray
, taken at periodic indices,
called a slice. To create a slice, use valarray
's operator[]
with an argument of type
slice
.
For some operations, the slice_array
object is transparent. In
particular, you can assign a valarray
to a slice_array
object (provided they have the
same size), or you can construct a new valarray
from a slice_array
.
If you want to perform other operations, such as
non-assignment arithmetic, you must explicitly convert the slice_array
to valarray
, as demonstrated in Example 13-47.
Example 13-47. Slicing a valarray
int main( ) { using namespace std; const int data[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13 }; valarray<int> v(data, sizeof(data)/sizeof(data[0])); const int newdata[] = { 30, 70, 110 }; valarray<int> rpl(newdata, 3); v[slice(2, 3, 4)] = rpl; cout << v << '\n'; // Prints: { 1 2 30 4 5 6 70 8 9 10 110 12 13} v[slice(3, 4, 2)] = -1; cout << v << '\n'; // Prints: { 1 2 30 -1 5 -1 70 -1 9 -1 110 12 13} valarray<int> mult(3, 2); v[slice(8, 2, 3)] *= mult; cout << v << '\n'; // Prints: { 1 2 30 -1 5 -1 70 -1 27 -1 110 36 13} cout << static_cast<valarray<int> >(v[slice(1, 5, 2)]) << '\n'; // Prints: { 2 -1 -1 -1 -1} cout << static_cast<valarray<int> >(v[slice(4, 3, 2)]) + static_cast<valarray<int> >(v[slice(2, 3, 2)]) << '\n'; // Prints: { 35 75 97} }
The members of slice_array
are straightforward. When using any of the assignment operators, the
valarray
on the righthand side
must be the same size as the slice_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
slice_array
so it can be used
only as a return value from valarray
's operator[]
.