fsfh60 fsfh60 - 8 months ago 60
C++ Question

Removing a string from a std::vector?

I have a

. I'd like to read in a string from the user and remove it from
. Here's what I have so far:

This produces an error.

Any ideas how we can make this to work? Do we first need to find the rnames and then erase it?


The std::vector's erase method takes in an iterator saying which entry in the vector you want to remove. It doesn't work like the map or set where you can call erase to remove a specified key.

To remove a single copy of an element from a std::vector, you can use std::find and the std::vector's erase member function like this:

auto itr = std::find(v.begin(), v.end(), rnames);
if (itr != v.end()) v.erase(itr);

The above code assumes you're using C++11, which all major modern compilers support. However, it seems like you're using an older compiler that doesn't support C++11, so you'd have to write something like this:

std::vector<string>::iterator itr = std::find(v.begin(), v.end(), rnames);
if (itr != v.end()) v.erase(itr);

To remove all copies of an element from a vector, you can use std::remove like this:

v.erase(std::remove(v.begin(), v.end(), rnames), v.end());

That being said, if you find that you are often removing elements from a std::vector and you have a large number of elements in the vector, you may want to consider changing data structures to something that more efficiently supports removals.