2

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.

4

2 に答える 2

9

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);
于 2012-11-22T21:56:37.617 に答える
1

You can use std::copy_backward for copying the objects (copy, not move), and then use std::vector::erase to remove the original objects.

For your example:

std::copy_backward(v.begin()+1, v.begin()+3, v.begin()+4);
v.erase(v.begin()+1, v.begin()+3);
于 2012-11-22T22:04:28.383 に答える