Click here to Skip to main content
15,748,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

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.
Updated 7-Apr-11 10:13am

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.
Share this answer
There is the oldie-goldie memmove[^]:
#include <cstring>
  int a[5] = {1, 2, 5, 2, 1};
  memmove(&a[1], &a[0], sizeof(a)-sizeof(a[0]));
Share this answer
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.
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.
Share this answer
If you use a fixed size array - use a circular seek pointer and you must not move anything. Thats the fastest method ever.
Share this answer
You could simply use memmove (or memmove_s) with the source starting at element [0] and the destination starting at element [1].

Good luck.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

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