slice class — Slice of an array
class slice { public: slice( ); slice(size_t, size_t, size_t); size_t start( ) const; size_t size( ) const; size_t stride( ) const; };
The slice
class describes a
slice of a valarray
. A slice is a
subset of the elements of a valarray
at periodic indices. The slice
has a starting index, a size, and a stride, in which the stride is
the index interval. Figure
13-28 depicts slice(1,3,4)
of a valarray
.
Use the subscript operator to take a slice of a valarray
. You can assign a valarray
to a slice, in which the
righthand side of the assignment must have the same size as the size
of the slice. You can also convert the slice to a valarray
, which copies only those elements
of the slice to the new valarray
.
When you take a slice of a valarray
, the result is a slice_array
object, but the slice_array
type is mostly transparent to
the programmer. See slice_array
later in this section for details.
You can use a slice to treat a valarray
as a two-dimensional matrix. A
slice can specify a row or column of the matrix. For an n
× m
matrix, row r
is slice
(r
*m
,
m
, 1), and column c
is slice
(c
, n
, m
), as you can see in Example 13-46.
Example 13-46. A simple 2-D matrix class
template<typename T> class matrix2D { public: matrix2D(std::size_t rows, std::size_t columns) : rows_(rows), cols_(columns), data_(rows * columns) {} std::size_t rows( ) const { return rows_; } std::size_t cols( ) const { return cols_; } std::valarray<T> row(std::size_t r) const { return data_[std::slice(r*cols( ),cols( ), 1)]; } std::valarray<T> col(std::size_t c) const { return data_[std::slice(c, rows( ), cols( ))]; } std::slice_array<T> row(std::size_t r) { return data_[std::slice(r*cols( ),cols( ), 1)]; } std::slice_array<T> col(std::size_t c) { return data_[std::slice(c, rows( ), cols( ))]; } T& operator( )(std::size_t r, std::size_t c) { return data_[r*cols( )+c]; } T operator( )(std::size_t r, std::size_t c) const { return row(r)[c]; } matrix2D<T> transpose( ) { matrix2D<T> result(cols( ), rows( )); for (std::size_t i = 0; i < rows( ); ++i) result.col(i) = static_cast<std::valarray<T> >(row(i)); return result; } private: std::size_t rows_; std::size_t cols_; std::valarray<T> data_; };