C++ <valarray> - shift() Function
The C++ valarray::shift function returns a new valarray of the same size with elements shifted left n spaces (or right if n is negative), with the new elements value-initialized. The new position of each element is (i − n), where i is the previous position.
Syntax
valarray shift (int n) const;
Parameters
n |
Specify number of elements to shift. If positive, it is shifted left. If negative, it is shifted right. |
Return Value
Returns valarray with shifted elements.
Time Complexity
Depends on library implementation.
Example:
The example below shows the usage of valarray::shift function.
#include <iostream> #include <valarray> using namespace std; int main (){ valarray<int> varr = {10, 20, 30, 40, 50}; cout<<"varr contains: "; for(int i = 0; i < varr.size(); i++) cout<<varr[i]<<" "; valarray<int> result1 = varr.shift(2); cout<<"\nvarr.shift(2) returns: "; for(int i = 0; i < result1.size(); i++) cout<<result1[i]<<" "; valarray<int> result2 = varr.shift(-2); cout<<"\nvarr.shift(-2) returns: "; for(int i = 0; i < result2.size(); i++) cout<<result2[i]<<" "; return 0; }
The output of the above code will be:
varr contains: 10 20 30 40 50 varr.shift(2) returns: 30 40 50 0 0 varr.shift(-2) returns: 0 0 10 20 30
❮ C++ <valarray> Library