std::slice_array - cppreference.com (original) (raw)

| | | | | ---------------------------------------- | | | | template< class T > class slice_array; | | |

std::slice_array is a helper template used by the valarray subscript operator with std::slice argument. It has reference semantics to a subset of the array specified by the std::slice object.

[edit] Member types

Type Definition
value_type T

[edit] Member functions

[edit] Example

#include #include   class Matrix { int dim; std::valarray data; public: explicit Matrix(int dim, int init = 0) : dim{dim}, data(init, dimdim) {} void clear(int value = 0) { data = value; } void identity() { clear(); diagonal() = 1; } int& operator()(int x, int y) { return data[dim * y + x]; }   std::slice_array diagonal() { return data[std::slice(0, dim, dim + 1)]; } std::slice_array secondary_diagonal() { return data[std::slice(dim - 1, dim, dim - 1)]; } std::slice_array row(std::size_t row) { return data[std::slice(dim * row, dim, 1)]; } std::slice_array column(std::size_t col) { return data[std::slice(col, dim, dim)]; } template<unsigned, unsigned> friend class MatrixStack; };   template class MatrixStack { std::valarray stack; unsigned count = 0; public: MatrixStack() : stack(dim * dim * max) {} void print_all() const { std::valarray row(dimcount); for (unsigned r = 0; r != dim; ++r) // screen row { row = stack[std::gslice(r * dim, {count, dim}, {dim * dim, 1})]; for (unsigned i = 0; i != row.size(); ++i) std::cout << row[i] << ((i + 1) % dim ? " " : " │ "); std::cout << '\n'; } } void push_back(Matrix const& m) { if (count < max) { stack[std::slice(count * dim * dim, dim * dim, 1)] = m.data[std::slice(0, dim * dim, 1)]; ++count; } } };   int main() { constexpr int dim = 3; Matrix m{dim}; MatrixStack<dim,12> stack;   m.identity(); stack.push_back(m);   m.clear(1); m.secondary_diagonal() = 3; stack.push_back(m);   for (int i = 0; i != dim; ++i) { m.clear(); m.row(i) = i + 1; stack.push_back(m); }   for (int i = 0; i != dim; ++i) { m.clear(); m.column(i) = i + 1; stack.push_back(m); }   m.clear(); m.row(1) = std::valarray{4, 5, 6}; stack.push_back(m);   m.clear(); m.column(1) = std::valarray{7, 8, 9}; stack.push_back(m);   stack.print_all(); }

Output:

1 0 0 │ 1 1 3 │ 1 1 1 │ 0 0 0 │ 0 0 0 │ 1 0 0 │ 0 2 0 │ 0 0 3 │ 0 0 0 │ 0 7 0 │ 0 1 0 │ 1 3 1 │ 0 0 0 │ 2 2 2 │ 0 0 0 │ 1 0 0 │ 0 2 0 │ 0 0 3 │ 4 5 6 │ 0 8 0 │ 0 0 1 │ 3 1 1 │ 0 0 0 │ 0 0 0 │ 3 3 3 │ 1 0 0 │ 0 2 0 │ 0 0 3 │ 0 0 0 │ 0 9 0 │

[edit] See also

| | proxy to a subset of a valarray after applying a gslice (class template) [edit] | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |