Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array shifting to the next element

Tags:

c++

arrays

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;
}
like image 422
Azam Avatar asked Sep 06 '10 09:09

Azam


2 Answers

#include<algorithm>

// ...
std::rotate(x, x+4, x+5);
x[0] = 6;
like image 69
wilhelmtell Avatar answered Oct 18 '22 20:10

wilhelmtell


#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;
}
like image 45
Cedric H. Avatar answered Oct 18 '22 19:10

Cedric H.