Jump to content
  • Advertisement
Sign in to follow this  
utilae

Erase specific element of vector using an index

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

Hi, I am using C++. I have a vector: m_vecIntegers and it has 10 elements (0-9) and I want to erase element 5. I want to use the erase function, eg vecIntegers.erase() but I cannot use an iterator, eg vecIntegers.erase(iter) I need to use an index, eg vecIntegers.erase(5) How do I do it?

Share this post


Link to post
Share on other sites
Advertisement
If are going to be regularly adding or removing elements from the middle of a std::vector you may want to use a different container - for example, std::list.

std::vector guarantees that it's elements are stored in contiguous memory - which means that if you remove element 5, every element after 5 will have to be moved. With a 10 element vector using POD types, this may not take too long - but if you have a very large vector or complex and large datatypes, this can become very expensive.

Share this post


Link to post
Share on other sites
Or if your constraints allow it, you could simply copy the last element to the one you want to delete and then pop the end.

Share this post


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

  • 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!