Shifting elements of an array?

May 15, 2008 at 10:36pm
I thought I read something about shifting all of the elements of an array to the left or right but I can't find anything on google. Is this possible or am I wrong. I'm making a blackjack game and this might come in handy. Thanks
May 16, 2008 at 1:33am
I am not familiar with this myself. However, if this doesn't exist, you maybe thinking of the shift-left and shift-right operators. These operate on bits though, not arrays.

Someone else might chime in with an Array function, but I am personally not familiar with one.
May 16, 2008 at 1:54am
Use memmove().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int main()
  {
  int a[ 10 ];

  // Fill the array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
  for (int i = 0; i < sizeof( a ) / sizeof( a[ 0 ] ); i++)
    a[ i ] = i;

  // shift up
  memmove( a +1, a, sizeof( a ) -sizeof( a[ 0 ] ) );

  // print it
  for (int i = 0; i < sizeof( a ) / sizeof( a[ 0 ] ); i++)
    cout << "a[ " << i << " ] = " << a[ i ] << endl;

  // shift down
  memmove( a, a +1, sizeof( a ) -sizeof( a[ 0 ] ) );

  // print it
  for (int i = 0; i < sizeof( a ) / sizeof( a[ 0 ] ); i++)
    cout << "a[ " << i << " ] = " << a[ i ] << endl;

  return EXIT_SUCCESS;
  }


I leave it as an exercise for you to stick this stuff in usefull functions.


Oh yeah, lest I forget:
If your array is of objects (and not unmanaged types: simple types and structs and the like) you must make sure to zero the element(s) on the end that were moved out. Otherwise you may find yourself with some serious memory corruption! (Objects are meant to be duplicated with their copy constructors, not by simply copying their bits as memmove() does.)
Last edited on May 16, 2008 at 1:57am
May 16, 2008 at 1:58am
Ahhh I knew someone else would have a way to do it :) Can't say I have ever used it, nor would I :P Looks like an easy way to develop a serious case of Memory Leak.
May 16, 2008 at 2:00am
Only if you aren't careful with the objects as I indicated. You should feel free to relocate an object in memory without side-effects.
May 16, 2008 at 2:00am
I think I will stick to manual moving when using standard arrays. Or the STL when I don't want to worry about that sorta thing :)
May 16, 2008 at 2:06am
Agreed. Any of the standard containers (vector, deque, list) allow very easy push/pop from the ends, which is essentially the same thing...

[edit]
But I would like to reiterate that using memmove() really isn't troublesome: for things like int/float/struct arrays using it is the same as doing it "manually", just much faster.
Last edited on May 16, 2008 at 2:09am
Topic archived. No new replies allowed.