Remove first N elements from a std::vector

前端 未结 3 1933
南笙
南笙 2020-12-24 13:42

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?

3条回答
  •  别那么骄傲
    2020-12-24 13:52

    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.

提交回复
热议问题