Name

gslice class — Generalized slice

Example

Notice also that the final gslice requires a const valarray. This is because it contains degenerate slices, in which an element (e.g., 8) appears more than once in the result. The aliasing rules of a valarray prohibit multiple references to the same element, so if a const valarray were not used, the results would be undefined. By using a const valarray, the result is a copy of the sliced elements, so the two occurrences of element 8 are separate objects, not aliases for the same object, and disaster is averted.

A generalized slice is most often used to represent a multidimensional array. For example, you can treat a valarray of 24 elements as a 2 × 3 × 4 matrix. To extract a plane of the matrix, you can use a gslice. Figure 13-27 depicts the matrix and the plane. Example 13-42 shows the code.

Example 13-42. Using gslice for multidimensional arrays

// SeeExample 13-41 for the va function.
int main(  )
{
  using namespace std;
  valarray<int> a(24);
  for (size_t i = 0; i < a.size(  ); ++i)
    a[i] = i;
  cout << a[gslice(1, va(2, 3), va(12, 4))] << '\n';
// Prints: { 1 5 9 13 17 21 }
}

To create an n-dimensional submatrix of an m-dimensional matrix, the size and stride arrays must both have length n. The size array determines the dimensions of the result.

Use the subscript operator to take a generalized slice of a valarray. You can assign a valarray to a generalized 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 generalized slice of a valarray, the result is a gslice_array object, but the gslice_array type is mostly transparent to the programmer. See gslice_array later in this section for details.