Sign in to follow this  
utilae

Erase specific element of vector using an index

Recommended Posts

utilae    188
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
Will F    1069
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
Mastaba    761
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this