简体   繁体   English

如何在c ++中向左或向右移动数组?

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

I have an array a[]={1,0,0,0,0}; 我有一个数组a[]={1,0,0,0,0}; and I want to rotate it so it ends up like this: a[] = {0,0,0,0,1}; 我想旋转它,所以它最终结束: 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> 在标头<algorithm>使用标准算法std::rotate声明

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. 如果你想让原始数组保持不变,你也可以使用标准算法std::rotate_copy

If you compiler does not support the range-based for loop then you can write 如果您的编译器不支持基于范围的for循环,那么您可以编写

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). 如果你有权访问C ++ 11,可以通过创建一个std::valarray然后使用它的cshift函数 (代表循环移位)来完成。

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 . std::valarray是一个对象,它被设计为C ++ 2011标准的一部分 ,用于保存值数组,然后轻松地对它们执行操作,例如数学运算符和常见函数(如swapshift

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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