简体   繁体   中英

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. 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. 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? Thanks.

You don't need std::copy to create a new vector with a subset of the first one. You can achieve this with the vector 's constructor and its iterators ( doc here ):

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.

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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