I can't seem to think of a reliable way (that also compacts memory) to remove the first N elements from a std::vector
. How would one go about doing that?
Since you mention that you want to compact memory, it would be best to copy everything to a new vector and use the swap idiom.
std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector);
-
8Or more succinctly,
std::vector<myvector::value_type>(myvector.begin()+N, myvector.end()).swap(myvector);
. – ildjarn Sep 8 '11 at 17:22 -
@ildjarn, thank you - I knew there was a way to do it with an unnamed temporary but I had a brain freeze. I've updated my answer using your exact text. – Mark Ransom Sep 8 '11 at 17:29
-
-
@FredOverflow, I think he copied that from me. I think you can, but I didn't test it. – Mark Ransom Sep 9 '11 at 1:43
-
@FredOverflow : Mark's correct, I copied it from him and didn't notice. Realistically it would of course be
myvector_t::value_type
ordecltype(myvector)::value_type
. – ildjarn Sep 9 '11 at 1:48
Use the .erase()
method:
// Remove the first N elements, and shift everything else down by N indices
myvec.erase(myvec.begin(), myvec.begin() + N);
This will require copying all of the elements from indices N+1 through the end. If you have a large vector and will be doing this frequently, then use a std::deque
instead, which has a more efficient implementation of removing elements from the front.
-
2
-
1@Adam Thanks! I don't know how I missed a straight-forward thing like that. Much appreciated! – ForeverLearning Sep 8 '11 at 17:35
-
@Mooing I did mention that in my post but for now, that is less of a concern for me. This will get me going for the moment although I would love to know if there is a way I can compact the memory too. – ForeverLearning Sep 8 '11 at 17:36
v.erase( v.begin(), v.size() > N ? v.begin() + N : v.end() );
Don't forget the check of the size, just in case.
-
1@Mooing Duck I missed that. In that case, he'll have to create a new vector:
std::vector<T>( v.begin() + std::min( N, v.size() ). v.end() )
– James Kanze Sep 8 '11 at 17:29
std::deque
interest you? It's way more efficient for this. – R. Martinho Fernandes Sep 8 '11 at 17:12typedef
judiciously enough. ;-] – ildjarn Sep 8 '11 at 17:51std:vector<T>
is contiguous andstd::deque
isn't, which matters a lot when interfacing with legacy code that expects a T*. But for such code, you might be able to not delete the first N elements, and pass&v[N]
instead. – MSalters Sep 8 '11 at 22:51