mike
mike

Reputation: 194

Shifting elements in array by N elements

I have an array where each 'element' is composed of 4 consecutive values. Upon update I move the array by 4 values towards the end and insert 4 new values in the beginning.

Shift:

int m = 4;
for (int i = _vsize - 1; i + 1 - m != 0; i--){
     _varray[i] = std::move(_varray[i - m]);
}

Insertion:

memcpy(&_varray[0], glm::value_ptr(new_element), 4 * sizeof(float));

where new_element is of type glm::vec4 containing said 4 new values.

Any suggestions on how to improve this?

(Right now Im only shifting by one element, but want the flexibility of being able to shift say 8 times, without having to put this in a loop)

Thank you.

Upvotes: 1

Views: 781

Answers (1)

Blastfurnace
Blastfurnace

Reputation: 18652

You can try std::copy_backward. You want to copy a range of values to another range in the same container. Since the ranges overlap and you are copying to the right you can't use regular std::copy but must use std::copy_backward instead.

int m = 4; // make this a multiple of your 'element' size
std::copy_backward(&_varray[0], &_varray[_vsize - m], &_varray[_vsize]);

There is also std::move_backward but that doesn't really matter since your float values aren't movable.

Upvotes: 2

Related Questions