Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Russell

Removing elements from C++ vector

This topic is 5227 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

To remove the last element of a vector, you just pop_back(). To remove the last N elements, there are three ways that I''m aware of. For std::vector v; 1. A for loop calling pop_back() repeatedly 2. erase(some_iterator, v.end()); 3. resize(v.size() - n) First question. Is it safe to assume that after any of these that the capacity() will remain the same? Second question. Which of these will be the most efficient? My guess is resize(), then erase(), then multiple calls to pop_back().

Share this post


Link to post
Share on other sites
Advertisement
The vector''s capacity should remain the same for all three methods.

Depending on STL implementation, quality of compiler and the type contained by the vector, it''s most likely that the erase() method will perform better than resize(). The reason being is that resize() has an implicit temporary object construction that, depending on it''s side effects would not be optimized away by a standards compliant compiler. I can''t think of any situation where resize() would perform better than erase() for this purpose. At best they would perform equivalently. However, the best course of action would be to profile the code in question on your compiler/STL implementation and see what works best for you.

Share this post


Link to post
Share on other sites
Okay, I''m told in IRC that resize() will erase all of the data that was there, which is not what I want. So erase() it is!

Share this post


Link to post
Share on other sites
You were told wrong. The elements contained by a vector that has resize() called on it should be identical up to the minimum of the old and new sizes.

Share this post


Link to post
Share on other sites
Yup. resize() tends to be implemented in terms of erase() and insert(), so if you know which of those you''ll actually be using you can save yourself at least a branch by calling it directly.


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!