如何将数组中的元素移动到下一个元素
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.
这是我目前所做的。这是错误的,这就是我在这里需要帮助的原因。提前致谢。
#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;
}
最佳答案
#include<algorithm>
// ...
std::rotate(x, x+4, x+5);
x[0] = 6;
关于c++ - 数组转移到下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3650372/