C++ Standard Library C++ STL Library

C++ <valarray> - cshift() Function



The C++ valarray::cshift function returns a new valarray of the same size with elements rotated left by n spaces (or rotated right if n is negative). The new position of each element is (i − n)%s, where i is the previous position and s is size of valarray.

Syntax

valarray cshift (int n) const;

Parameters

n Specify number of elements to rotate. If positive, it is rotated left. If negative, it is rotated right.

Return Value

Returns valarray with circularly shifted elements.

Time Complexity

Depends on library implementation.

Example:

The example below shows the usage of valarray::cshift 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.cshift(2);
  cout<<"\nvarr.cshift(2) returns: ";
  for(int i = 0; i < result1.size(); i++)
    cout<<result1[i]<<" "; 

  valarray<int> result2 = varr.cshift(-1);
  cout<<"\nvarr.cshift(-1) 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.cshift(2) returns: 30 40 50 10 20 
varr.cshift(-1) returns: 50 10 20 30 40

❮ C++ <valarray> Library