简体   繁体   English

如何使用STL的copy()从现有矢量创建新矢量?

[英]How do I use STL's copy() to create a new vector from an existing vector?

Say I have a std::vector called vec with 10 elements and I want to create a new std::vector containing all elements between (and including) the 2nd and 5th elements of vec. 说我有一个std::vector称为vec有10个元素,我想创建一个新std::vector包含之间的所有元素(包括)第2和VEC的第五元素。 I can see how I might write a for loop to do this, but it looks like STL's copy() can do this more concisely. 我可以看到如何编写for循环来执行此操作,但是看起来STL的copy()可以更简洁地执行此操作。 But I'm not really getting iterators: I've seen how you can use start() and end() to iterate over a vector from its first to last element, but what about the situation above, where I want something slightly different? 但是我并没有真正获得迭代器:我已经看到了如何使用start()end()从其第一个元素到最后一个元素对向量进行迭代,但是上面的情况又如何呢? Thanks. 谢谢。

You don't need std::copy to create a new vector with a subset of the first one. 您不需要std::copy来创建带有第一个vector的子集的新vector You can achieve this with the vector 's constructor and its iterators ( doc here ): 您可以使用vector的构造函数及其迭代器( 在此处doc )实现此目的:

std::vector<myType> vec = ...;
std::vector<myType> other(vec.begin() + 1, vec.begin() + 5);

You have to be sure though, that you don't exceed the vector 's limits, or you will get undefined behavior. 但是,您必须确保不超过vector的限制,否则您将获得未定义的行为。

Constantinus is right with his answer - you don't need copy. 康斯坦丁努斯的回答是正确的-您不需要复制。

But in case of a different situation, where you want to append elements you can use this: 但是在其他情况下,要附加元素,可以使用以下命令:

std::vector< type > vec = ... ;
std::vector< type > othervec = ...;
std::copy( vec.begin(), vec.end(), std::back_inserter(othervec) );

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

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