在 C++ 中切片向量

2021-12-21 00:00:00 python slice vector 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()

相关文章