Slicing a vector in C++(在 C++ 中切片向量)
问题描述
在 C++ 中,是否有等效的列表切片 [1:]
来自 Python 的向量?我只想从向量中获取除第一个元素之外的所有元素.
Is there an equivalent of list slicing [1:]
from Python in C++ with vectors? I simply want to get all but the first element from a vector.
Python 的列表切片操作符:
Python's list slicing operator:
list1 = [1, 2, 3]
list2 = list1[1:]
print(list2) # [2, 3]
C++ 期望的结果:
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2;
v2 = v1[1:];
std::cout << v2 << std::endl; //{2, 3}
推荐答案
这可以使用 std::vector
的复制构造函数轻松完成:
This can easily be done using std::vector
's copy constructor:
v2 = std::vector<int>(v1.begin() + 1, v1.end());
正如@AlessandroFlati 建议的那样,我应该澄清这将包括 v1.end()
As @AlessandroFlati suggested I should clarify that this will include v1.end()
这篇关于在 C++ 中切片向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中切片向量


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07