indirect_array class template — Helper class for indirect arrays
template <typename T> class indirect_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&); ~indirect_array( ); private: indirect_array( ); indirect_array(const indirect_array&); indirect_array& operator=(const indirect_array&); };
The indirect_array
class
template represents a subset of the elements of a valarray
. To create an indirect subset,
use valarray
's operator[]
with an argument of type
valarray<size_t>
. The
elements of the argument are the desired indices in the
subset.
For some operations, the indirect_array
object is transparent. In
particular, you can assign a valarray
to an indirect_array
object (provided they have
the same size), or you can construct a new valarray
from an indirect_array
.
If you want to perform other operations, such as
non-assignment arithmetic, you must explicitly convert the indirect_array
to valarray
, as demonstrated in Example 13-44.
Example 13-44. Using indirect_array
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 } // Specify the indices into a. const size_t p[] = { 2, 3, 5, 7 }; valarray<size_t> indices(p, sizeof(p)/sizeof(p[0])); cout << a[indices] << '\n'; // Prints: { 3 4 6 8 } // Add 10 to the elements at the desired indices. valarray<int> ten(10, 4); a[indices] += ten; cout << a << '\n'; // Prints: { 1 2 13 14 5 16 7 18 } // Must cast to perform ordinary arithmetic. cout << static_cast<valarray<int> >(a[indices]) * ten << '\n'; // Prints: { 130 140 160 180 } }
The members of indirect_array
are straightforward. When
using any of the assignment operators, the valarray
on the righthand side must be the
same size as the indirect_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 indirect_array
so it can be used only as a
return value from valarray
's
operator[]
.