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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With