HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Best way to extract a subvector from a vector?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromextractsubvectorbestvectorway

Problem

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::const_iterator first = myVec.begin() + 100000;
vector::const_iterator last = myVec.begin() + 101000;
vector newVec(first, last);


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

Code Snippets

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

Context

Stack Overflow Q#421573, score: 497

Revisions (0)

No revisions yet.