c++stlvectorrange

Best way to extract a subvector from a vector?


Suppose I have a std::vector (let's call it myVec) of size N. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, myVec [100000] through myVec [100999] in a vector of size 150000.

If this cannot be done efficiently with a vector, is there another STL datatype that I should use instead?


Solution

  • vector<T>::const_iterator first = myVec.begin() + 100000;
    vector<T>::const_iterator last = myVec.begin() + 101000;
    vector<T> newVec(first, last);
    

    It's an O(N) operation to construct the new vector, but there isn't really a better way.