我想像在 Python 中那样在 C++ 中“环绕”一个列表/vector 。基本上我想将元素从列表的末尾移动到列表的开头。我不想明确地制作一个新列表。
在 Python 中我可以这样写:
my_list = [1, 2, 3, 4, 5]
#[1, 2, 3, 4, 5]
q = collections.deque(my_list)
q.rotate(3)
#deque([3, 4, 5, 1, 2])
我查看了 STL 中的双端队列,但没有看到任何与旋转类似的东西。似乎应该有一种简单的方法可以使用迭代器或类似的东西来做到这一点。
最佳答案
您正在寻找std::rotate
来自标准库,它提供了一种使用迭代器执行此操作的简单方法。
#include <algorithm>
std::vector<T> v /* = populate() */;
std::rotate(v.begin(), v.begin() + 3, v.end());
可以使用任何前向迭代器,因此这适用于大多数(序列)容器。
关于c++ - 像在 Python 中一样环绕 C++ vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739255/