旋转具有特定旋转次数的数组

Rotation of an array with specific number of rotation

所以我尝试执行给定次数的旋转操作。

#include <iostream>
using namespace std;
void result_arr_one_rotation (int arr [], int n){
  // int one_rotate_arr[n];
  int p=arr[0];
   for (int i=0;i<n-1;++i){
    arr[i]=arr[i+1];
  }
  arr[n]=p;
  //return arr;
}


int main(){
//n stands for total number of elements in array and d stands for number of rotation
  int n,d;
  cin>>n>>d;
  int arr[n];
  //to take elements of array
  for(int i=0;i<n;i++){
    cin>>arr[i];
  }
  //int rotated_arr[n];
  for (int i=0;i<d;i++){
      result_arr_one_rotation(arr,n);
      //cout<<arr[i]<<" ";
  }
  for (int i=0;i<n;i++){
    cout<<arr[i]<<" ";
  }

  return 0;
}

现在,函数 result_arr_one_rotation 将元素旋转一个 index.To 存储我创建的第 0 个索引元素 p 最后分配的变量。您可以通过 'arr[n]=p' 行看到。现在,我已经旋转了 d 次,因为用户可以自由使用旋转的次数。 然后我简单地打印出元素。

当我给出像

这样的输入时,问题就来了
5 which is number of elements(n)
2 number of rotation d
1 2 3 4 5 -> answer it should be
3 4 5 5 5-> this is the answer comes out

谁能告诉我我做错了什么?

您在此循环中使用的最后一个索引

for (int i=0;i<n-1;++i){
    arr[i]=arr[i+1];
}

n-2。数组中的有效索引为 0 到 size-1。这里

arr[n]=p;

您越界访问数组。如果你想分配给最后一个元素,那就是 arr[n-1] = p;

如果你不想使用 std::rotate 因为这是一个练习,我仍然会敦促你使用 std::vector,因为你使用的是可变长度数组,这不是标准的 C++。实际上在 C++ 中并不需要 VLA,因为它有 std::vector。它们更像是 C 的东西,gcc 也在 C++ 中将它们作为非标准扩展提供。