Public Group

# Removing an item from std::vector

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

## Recommended Posts

Hi. In the text based rpg I'm writing, I'm using a std::vector (in C++) for the character's inventory. I need to figure out a way to remove items from the vector. I can't use pop_back() because the item may not be the last item in the vector. The item may also not be the only instance of the particular item in the vector either. Any help is appreciated.

##### Share on other sites
If you have an iterator to a vector element you can erase that element by using the erase() member function. Ex: my_vector.erase(my_vector.begin()) will erase the first element of the vector. To remove element n from the vector you can use my_vector.erase(my_vector.begin() + n).

If you want to remove all elements of a given value in the vector you can use the remove-erase idiom. It look like:
my_vector.erase( std::remove(my_vector.begin(), my_vector.end(), SOME_VALUE),                 my_vector.end() );

This first copies over the elements that needs to be removed from the vector with elements later in the vector and then erases the excess elements from the vector.

If you have a criteria for removing elements from the vector you can use remove_if() instead:
my_vector.erase( std::remove_if(my_vector.begin(), my_vector.end(), &some_function),                 my_vector.end() );

In this case some_function would be a function that accepts vector elements as an argument and returns true if you want to remove the element from the vector.

##### Share on other sites
You can use the erase() function in your vector IIRC, just pass it the iterator of the element you wish to remove.

You can also pass two iterators as parameters, and it will erase the elements between (and including) them. Might be useful if you have duplicate items next to eachother in the vector.

Anyways, hope that works

edit: whoops, bit too slow :p

• 10
• 18
• 14
• 18
• 15