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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With