如何在 STL 容器中移动元素

How can I shift elements inside STL container(如何在 STL 容器中移动元素)

本文介绍了如何在 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 容器中移动元素

基础教程推荐