Feb 11, 2017 at 9:06am UTC
hiya, how do I move an array's element up one value, like
array[2] = array[1]
array[3] = array[2]
array[4] = array[3]
etc..
Feb 11, 2017 at 9:59am UTC
What happens to the first element?
What happens to the last element?
To rotate the elements of the array, do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
static constexpr int sz = 6;
int array[sz] = {1, 2, 3, 4, 5, 6};
void print_array() {
for (int i = 0; i < sz - 1; ++i)
std::cout << array[i] << ", " ;
std::cout << array[sz - 1] << "\n" ;
}
int main() {
print_array();
auto const target_elt = array[sz - 1];
for (int i = 5; i > 0; --i)
array[i] = array[i - 1];
array[0] = target_elt;
print_array();
}
http://coliru.stacked-crooked.com/a/acdea3c375f03cb1
Last edited on Feb 11, 2017 at 10:00am UTC
Feb 11, 2017 at 10:07am UTC
1 2 3 4 5 6 7 8 9
//consider int arr[10];
int temp=arr[10-1];
for (int unsigned i=10; i>0;--i)
arr[i]=arr[i-1];
arr[0]=temp;
Array before shifting
Array after shifting
Last edited on Feb 11, 2017 at 10:11am UTC
Feb 11, 2017 at 4:29pm UTC
memmove function can do this better and faster.
Ive used it to make a side-scroller graphical program, for example, shifting all the pixels over and drawing new only on the edge.
Last edited on Feb 11, 2017 at 4:30pm UTC