Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to shift elements inside container on any positions to the left or right. The shifting elements are not contiguous.

e.g I have a vector {1,2,3,4,5,6,7,8} and I want to shift {4,5,7} to the left on 2 positions, the expected result will be {1,4,5,2,7,3,6,8}

Is there an elegant way to solve it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
395 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can write your own shifting 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);
}

You can then use it like that:

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 shifting multiple elements, find will iterate many times on the beginning of the container. Moreover, it assumes that every element is unique, which might not be the case. However, I hope it gave you some hints on how to implement what you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...