Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
An̲̳̳drew Avatar asked Jan 07 '09 18:01

An̲̳̳drew


People also ask

How do you retrieve an element from a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do I get a subvector?

Getting a subvector from a vector in C++auto last = v. begin() + n + 1. Declare a variable vector of vector type. Pass the value of first and last position of vector.


1 Answers

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.

like image 119
Greg Rogers Avatar answered Sep 28 '22 03:09

Greg Rogers