Remove first N elements from a std::vector

前端 未结 3 1890
南笙
南笙 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:47

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 13:53
    v.erase( v.begin(), v.size() > N ?  v.begin() + N : v.end() );
    

    Don't forget the check of the size, just in case.

    0 讨论(0)
提交回复
热议问题