Valarray slice selector : This class represents a valarray slice selector. It does not contain nor refers to any element – it only describes a selection of elements to be used as an index in valarray::operator.
std::slice is the selector class that identifies a subset of std::valarray. An object of type std::slice holds three values: the starting index, the stride, and the total number of values in the subset. Objects of type std::slice can be used as indexes with valarray’s operator.
In simple terms it is used to slice based on an index. A valarray slice is defined by a starting index, a size, and a stride.
slice( std::size_t start, std::size_t size, std::size_t stride ); size_t star : is the index of the first element in the selection size_t size : is the number of elements in the selection stride : is the span that separates the elements selected.
- In given Syntax, by default constructor isequivalent to slice(0, 0, 0). This constructor exists only to allow construction of arrays of slices.
- It constructs a new slice with parameters start, size, stride. This slice will refer to size number of elements, each with the position:
start + 0*stride start + 1*stride .... .... start + (size-1)*stride
slice(1, 5, 4) Input : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output : 1 5 9 13 17 Explanation : starting from index 1 then next index 1 + 1 * 4 = 5, next index 1 + 2 * 4 = 9, next index 1 + 3 * 4 = 13, next index 1 + 4 * 4 = 17.
Therefore, a slice with a stride higher than 1 does not select contiguous elements in the valarray. For example, slice(3, 4, 5) selects the elements 3, 8, 13 and 18.
slice(2, 3, 4): 2 6 10
Application : A simple application of slice is finding the trace of a matrix.
1 2 3 4 5 6 7 8 9 Trace of matrix is : 15
This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.