gpt4 book ai didi

c++ - 如何移动STL容器内的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:17 25 4
gpt4 key购买 nike

我想将容器内的元素在任何位置向左或向右移动。移动元素不连续。

例如我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com