繁体   English   中英

像在Python中一样包装C ++向量

[英]Wrap around C++ vector like in Python

我想在Python中“包装”C ++中的列表/向量。 基本上我想将元素从列表末尾切换到列表的开头。 我不想明确地制作新的清单。

在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看了deque,但是我没有看到任何类似旋转的东西。 似乎应该有一个简单的方法来使用迭代器或类似的东西。

您正在寻找标准库中的std::rotate ,它提供了一种使用迭代器执行此操作的简便方法。

#include <algorithm>

std::vector<T> v /* = populate() */;
std::rotate(v.begin(), v.begin() + 3, v.end());

可以使用任何前向迭代器,因此这适用于大多数(序列)容器。

你可以用

#include <algorithm>
std::reverse(my_list.begin(),my_list.end());

或使用

reverse_iterator rbegin();

在向量中向后循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM