Array shifting to the next element

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

How can I move elements in an array to the next element

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. 

This what I've done so far. It's wrong, that's why I need help here. Thanks in advance.

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

回答1:

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


回答2:

#include<algorithm>  // ... std::rotate(x, x+4, x+5); x[0] = 6; 


回答3:

To "move rightwards" you have to iterate from the end of array:

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

otherwise you just overwrite all the elements with the 0th element.

Please note array_size - 2 - otherwise you have "off by one" trying to access the element beyond the array end and that's undefined behavior.



回答4:

First of all, you should shift the old values in the array before you write the new value. But instead of a loop, you are better of using memmove(). Or even better with std::vector instead of an array - it handles all these low-level issues for you, including automatically resizing the array when needed.



回答5:

In the general case where you need to shift m elements (where 0 <= m <n): Start from the end of the array. If you start at the begining (index 0) then you overwrite and then move that overridden value.

Studying the source code of std::memmove may be instructive as well.



回答6:

You can start from the end of the array. You copy the

  • element in 2nd last position to the last position,
  • element in 3rd last position to the 2nd last position,
  • ....
  • element in first position(index 0) to the 2nd position and finally
  • copy the new number in the first position. .

.

for(j = array_size-1; j >0; j--) {  x[j] = x[j-1]; } x[0] = 6; 


回答7:

    #include <iostream>      using namespace std;      int main()      {        int x[5] = { 5, 4, 3, 2, 1 };          int array_size = sizeof(x) / sizeof(x[0]);          int m = 1;          for(int j = array_size-1; j > 0; j--) {            x[j] = x[j-m];            cout << x[j] << endl;         }         x[0] = 6;        return 0;     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!