Reputation:
I have dynamic array with user-defined type:
std::vector<Pipe> pipes = {Pipe(640),Pipe(480),Pipe(320),Pipe(160)};
then I want to remove last element of an array, move all elements by 1 to the right and insert another Pipe()
at index of 0. For now I've got:
pipes.pop_back();
pipes.insert(pipes.begin(),Pipe(inf * 160);
inf++;
Note this is in a loop and initial value of inf is 5. I print values from Pipe class - constructor parameter is stored in a variable - at the end and they should be: 800, 640, 480, 320.
Instead they are: 800, 480 , 320 , 160. And after another iteration : 960, 640 , 320, 160.
That's because I'm just replacing the pipes[0] with another value before "moving" the array. So my question is how do I do that?
Also sorry for bad explanation I'm still learning.
Upvotes: 2
Views: 314
Reputation: 117856
You could use std::rotate
to move everything to the right by 1 element. Then assign a new Pipe
to the 0
element.
#include <algorithm>
// Move all elements to the right by 1
std::rotate(pipes.begin(), std::next(pipes.begin()), pipes.end());
// Create a new Pipe at the beginning
pipes[0] = Pipe(inf * 160);
Upvotes: 4