std::slice (Valarray slice selector)
Last Updated :
05 Oct, 2017
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[].
class slice;
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.
Syntax :
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.
Example:
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.
#include <iostream> // std::cout
#include <cstddef> // std::size_t
#include <valarray> // std::valarray, std::slice
int main()
{
std::valarray< int > sample(12);
for ( int i = 0; i < 13; ++i)
sample[i] = i;
std::valarray< int > bar = sample[std::slice(2, 3, 4)];
std::cout << "slice(2, 3, 4):" ;
for (std:: size_t n = 0; n < bar.size(); n++)
std::cout << ' ' << bar[n];
std::cout << '\n' ;
return 0;
}
|
Output:
slice(2, 3, 4): 2 6 10
Application : A simple application of slice is finding the trace of a matrix.
#include <iostream> // std::cout
#include <valarray> // std::valarray, std::slice
using namespace std;
int main()
{
int row = 3, col = 3;
std::valarray< int > matrix(row * col);
for ( int i = 0; i < row * col; ++i)
matrix[i] = i + 1;
std::valarray< int > diagonal = matrix[std::slice(0, col, col + 1)];
int index = 0;
for ( int i = 0; i < row; i++) {
for ( int j = 0; j < col; j++)
std::cout << matrix[index++] << " " ;
std::cout << endl;
}
int sum = 0;
for ( int i = 0; i < diagonal.size(); i++)
sum += diagonal[i];
std::cout << "Trace of matrix is : " ;
std::cout << sum << endl;
return 0;
}
|
Output:
1 2 3
4 5 6
7 8 9
Trace of matrix is : 15
Share your thoughts in the comments
Please Login to comment...