How can I shift elements inside STL container(如何在 STL 容器中移动元素)
问题描述
我想将容器内的元素向左或向右移动.移位元素不连续.
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);
}
然后你可以这样使用它:
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}
这是一个幼稚的实现,因为当移动多个元素时,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 容器中移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 STL 容器中移动元素


基础教程推荐
- C语言数组 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
- 总计将在节日礼物上花多少钱 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++多态 1970-01-01
- C语言3个整数的数组 1970-01-01