我想在容器内的任何位置向左或向右移动元素。换挡元件不是连续的。
例如,我有一个 vector {1,2,3,4,5,6,7,8},并且我想将{4,5,7}向左移动2个位置,则预期结果将为{1,4 ,5,2,7,3,6,8}
有解决问题的优雅方法吗?
最佳答案
您可以编写自己的移位功能。这是一个简单的例子:
#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
将在容器的开头多次迭代。而且,它假定每个元素都是唯一的,但事实并非如此。但是,我希望它能为您提供一些有关如何实现所需内容的提示。关于c++ - 如何在STL容器中移动元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/460583/