简体   繁体   中英

How to move elements in std::vector by 1?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM