如何在STL容器内移动元素

时间:2009-01-20 09:31:53

标签: c++ stl containers

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

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

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

2 个答案:

答案 0 :(得分: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);
}

然后你可以这样使用它:

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}

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

答案 1 :(得分:0)

你不能做一个简单的插入然后擦除吗?

不要忘记,您将使引用删除或插入点上方元素的任何迭代器无效,以最低者为准。

HTH

欢呼声,

罗布

相关问题