如何在STL容器中移动元素 [英] How can I shift elements inside STL container
问题描述
我想将容器内的元素在任何位置向左或向右移动。
I want to shift elements inside container on any positions to the left or right. The shifting elements are not contiguous.
例如,我有一个向量{1,2,3,4,5,6,7,8},我想移动{ 4,5,7}向左移动2个位置,预期结果将是{1,4,5,2,7,3,6,8}
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 ?
推荐答案
您可以编写自己的移位功能。这里有一个简单的例子:
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);
}
您可以这样使用:
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
将在容器的开头迭代许多次。此外,它假定每个元素是唯一的,这可能不是这样。但是,我希望它给你一些提示如何实现你需要的。
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.
这篇关于如何在STL容器中移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!