数组转移到下一个元素

Aza*_*zam 6 c++ arrays

如何将数组中的元素移动到下一个元素

eg: x[5] = { 5, 4, 3, 2, 1 }; // initial values
    x[0] = 6; // new values to be shifted
    x[5] = { 6, 5, 4, 3, 2 }; // shifted array, it need to be shifted, 
                              // not just increment the values.
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所做的.这是错的,这就是我在这里需要帮助的原因.提前致谢.

#include <iostream>

using namespace std;

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

  int array_size = sizeof(x) / sizeof(x[0]);

  x[0] = 6;

  int m = 1;

  for(int j = 0; j < array_size; j++) {
    x[m+j] = x[j];
    cout << x[j] << endl;
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

wil*_*ell 14

#include<algorithm>

// ...
std::rotate(x, x+4, x+5);
x[0] = 6;
Run Code Online (Sandbox Code Playgroud)

  • +1来自我实际提供C++解决方案. (5认同)

sha*_*oth 8

要"向右移动",你必须从数组的末尾迭代:

for(int j = array_size - 2; j >= 0; j--) {
   x[m+j] = x[j];
   cout << x[j] << endl;
}   
Run Code Online (Sandbox Code Playgroud)

否则你只需用第0个元素覆盖所有元素.

请注意array_size - 2- 否则你有"一个接一个"试图访问数组末端之外的元素,这是未定义的行为.


Ced*_* H. 8

#include <iostream>

int main () {

  int x[5] = { 5, 4, 3, 2, 1 };

  int array_size = sizeof (x) / sizeof (x[0]);

  for (int j = array_size - 1; j > 0; j--) {

      x[j] = x[j - 1];
  }

  x[0] = 6;

  for (int j = 0; j < array_size; j++) {

      std::cout << x[j];
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)