简体   繁体   中英

How to shift an array to left or right in c++?

I have an array a[]={1,0,0,0,0}; and I want to rotate it so it ends up like this: a[] = {0,0,0,0,1};

how can I shift one element to the left or more then one?

#include<iostream.h>

int main ()
{                      
     int temp,a[] = {1,0,0,0,0};              
     for(int i =0;i<=4;i++)
     {
        temp = a[0];
        a[i] = a[i-1];
        a[4] = temp;  
        cout << a[i];
     }
    system("pause");
    return 0;
}

Use standard algorithm std::rotate declared in header <algorithm>

For example

#include <iostream>
#include <algorithm>
#include <iterator>

int main() 
{
    int a[] = { 1, 0, 0, 0, 0 };
    std::rotate( std::begin( a ), std::next( std::begin( a ) ), std::end( a ) );

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

The output is

0 0 0 0 1

Statement

    std::rotate( std::begin( a ), std::next( std::begin( a ) ), std::end( a ) );

can be written simpler

    std::rotate( a, a + 1, a + 5 );

ALso you can use standard algorithm std::rotate_copy if you want to have the original array unchanged.

If you compiler does not support the range-based for loop then you can write

for ( size_t i = 0; i < 5; i++ ) std::cout << a[i] << ' ';

If you have access to C++11, this can be done by creating an std::valarray and then using it's cshift function (which stands for circular-shift).

An std::valarray is an object that was designed, as a part of the C++ 2011 standard , to hold an array of values, and then easily perform operations on them, such as mathematical operators and common functions like swap or shift .

As an example:

#include <valarray>

int main()
{
  int myInts[] = {1,2,3,4,5};

  std::valarray<int> myValArray(myInts, 5);  // 1 2 3 4 5
  myValArray = myValArray.cshift(2);         // 3 4 5 1 2 - rotated left
  myValArray = myValArray.cshift(-1);        // 2 3 4 5 1 - rotated right

  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM