15,748,330 members
See more:
Hey,

Quick question, and feel free to just point me at a class or FAQ. Is there a faster or more efficient way to do the following? Just slide values down an array:

int a[5] = {1, 2, 5, 2, 1};

a[4] = a[3];
a[3] = a[2];
a[2] = a[1];
a[1] = a[0];

a[0] = //Some input

I'm just looking for a way to slide all the values down by 1 place. Thanks in advance for answering my trivial question.
Posted
Updated 7-Apr-11 10:13am
v2

## Solution 1

Use a collection instead of an array. If you can't do that, allocate a new array that's one element larger, and then move the other array into the new one starting at element 1 in the new array.

## Solution 2

There is the oldie-goldie memmove[^]:
C++
#include <cstring>
//...
int a[5] = {1, 2, 5, 2, 1};
memmove(&a[1], &a[0], sizeof(a)-sizeof(a[0]));

v2
Donald Hume 7-Apr-11 16:13pm
Oh man what a silly mistake, anyway I fixed it for clarity's sake.

Pallini is that method any more efficient than just moving it myself?
CPallini 7-Apr-11 21:13pm
OK, I removed the first part of my answer according.
As about the performance, see Nish's replay. It makes sense to me.

## Solution 5

Calls like memmove will most likely be optimized to take advantage of block-memory move intrinsic operations, although a decent compiler would see your for-loop (or sequential code, whatever you have), and replace it with a memmove during compilation. You could run some performance tests if this is a major factor, although if it's just a few hundred or even 1000 elements you are talking about, it probably does not matter much.

## Solution 3

If you use a fixed size array - use a circular seek pointer and you must not move anything. Thats the fastest method ever.
Regards.

## Solution 4

You could simply use memmove (or memmove_s) with the source starting at element [0] and the destination starting at element [1].

Good luck.

Top Experts
Last 24hrsThis month
 Rick York 40 Graeme_Grant 40 JudyL_MD 40 OriginalGriff 40 CHill60 10
 OriginalGriff 165 Graeme_Grant 150 Richard MacCutchan 60 Rick York 40 JudyL_MD 40

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900