How can I move elements inside an STL container

I want to move elements inside the container in any position left or right. Moving items are not adjacent.

for example, I have a vector {1,2,3,4,5,6,7,8} and I want to shift {4,5,7} to the left by 2 positions, the expected result will be {1,4,5, 2,7,3,6,8}

Is there an elegant way to solve it?

+6
c ++ stl containers
source share
2 answers

You can write your own switching function. Here's a simple one:

#include <iterator> #include <algorithm> template <typename Container, typename ValueType, typename Distance> void shift(Container &c, const ValueType &value, Distance shifting) { typedef typename Container::iterator Iter; // Here I assumed that you shift elements denoted by their values; // if you have their indexes, you can use advance Iter it = find(c.begin(), c.end(), value); Iter tmp = it; advance(it, shifting); c.erase(tmp); c.insert(it, 1, value); } 

Then you can use it like this:

 vector<int> v; // fill vector to, say, {1,2,3,4,5} shift(v, 4, -2); // v = {1,4,2,3,5} shift(v, 3, 1); // v = {1,4,2,5,3} 

This is a naive implementation, because when you move multiple items, find will be repeated many times at the beginning of the container. Moreover, he suggests that each element is unique, which may not be. However, I hope that he gave you some tips on how to implement what you need.

+3
source share

Can you do a simple paste and then delete?

Remember that you will invalidate any iterators that reference elements above the delete or insertion point, whichever is less.

NTN

amuses

Rob

0
source share

All Articles