Jump to content
  • Advertisement
Sign in to follow this  
Cable_pair

Removing an item from std::vector

This topic is 4402 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. 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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!