Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relocate a part of a vector

Tags:

c++

std

vector

I'd like to take out a range from a vector (remove the items) and insert them in the same order in the same vector, but at an other location.

Example:

                  0 1 2 3 4 5
Original vector:  A B C D E F

Take range 1-3 and insert at (after) 4.

                  0 1 2 3 4 5
Resulting vector: A E B C D F


I could probably do this with for loops, or using remove_copy and insert. Is there a better/faster way? What I don't like with remove_copy is that I have to specify a value that should not be removed. I want to move all of them and I'm not sure I can specify a value that never occurs in the vector.

like image 221
Jawap Avatar asked Feb 01 '26 08:02

Jawap


1 Answers

You want std::rotate:

#include <vector>
#include <algorithm>

//                           |<---------->|<->|          <-- rotate this range
std::vector<char> v = { 'A', 'B', 'C', 'D', 'E', 'F' };

std::rotate(v.begin() + 1, v.begin() + 4, v.begin() + 5);
like image 127
Kerrek SB Avatar answered Feb 03 '26 23:02

Kerrek SB