Advertisement Jump to content
Sign in to follow this  

C++ STL, deleting elements

This topic is 5020 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

Note that this is an O(n) operation. (If order does not matter, you could swap the element to be deleted with the last element; deleting the last element is O(1).)

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
To round this out a little:

If you erase an element or a few elements, all the elements following are shifted up. This means that the index you would have used to access them before is now not the same (and may even be invalid). So be warned...

If you are wanting to add or delete elements in the middle of a container then it may be more suitable for you to use a std::list. If you only want to add remove them from the end then std::deque may be the best choice.

If your container is storing objects rather than pointers to objects, erasing and inserting will be costly as the objects will have to be copied. If they are large objects then it could be very costly.

It may be more efficient to store pointers to objects. This makes it easier to insert and erase them as its simple pointers that are being shoved around rather than the objects themselves. This means though that you have to look after the allocation and deallocation of the actual objects pointed to. To make this easier, many people use smart pointers; in particular boost.shared_ptr.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!