在 C++ 中切片向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50549611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Slicing a vector in C++
提问by Wizard
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.
是否有等效[1:]
于在 C++ 中使用向量从 Python切片的列表?我只想从向量中获取除第一个元素之外的所有元素。
Python's list slicing operator:
Python 的列表切片操作符:
list1 = [1, 2, 3]
list2 = list1[1:]
print(list2) # [2, 3]
C++ Desired result:
C++ 期望的结果:
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2;
v2 = v1[1:];
std::cout << v2 << std::endl; //{2, 3}
回答by DimChtz
This can easily be done using std::vector
's copy constructor:
这可以使用std::vector
的复制构造函数轻松完成:
v2 = std::vector<int>(v1.begin() + 1, v1.end());
回答by Adrian
回答by Mankodaiyan
You can follow the above answer. It's always better to know multiple ways.
你可以按照上面的回答。了解多种方法总是更好。
int main
{
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2{v1};
v2.erase( v2.begin() );
return 0;
}