如何在STL容器内移动元素

Ser*_*rik 6 c++ containers stl

我想将容器内的元素移到左侧或右侧的任何位置.换档元件不是连续的.

例如,我有一个向量{1,2,3,4,5,6,7,8},我想在{2,5,7}向左移动2个位置,预期结果为{1,4 ,5,2,7,3,6,8}

有没有一种优雅的方法来解决它?

Luc*_*lle 3

您可以编写自己的移位函数。这是一个简单的:

#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);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

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}
Run Code Online (Sandbox Code Playgroud)

这是一个幼稚的实现,因为当移动多个元素时,find将在容器的开头迭代多次。此外,它假设每个元素都是唯一的,但情况可能并非如此。不过,我希望它能给您一些关于如何实现您所需要的提示。