How do I remove an item from a stl vector with a certain value?

I was considering the API documents for stl vector, and also saw there was no method on the vector class that permitted the elimination of a component with a particular value. This feels like an usual procedure, and also it appears weird that there is no constructed in means to do this.

2022-06-07 15:56:57
Source Share
Answers: 5

The various other solutions cover just how to do this well, yet I assumed I would certainly additionally mention that it is not actually weird that this isn't in the vector API: it mishandles, straight undergo the vector for the value, adhered to by a number of duplicating to remove it.

If you are doing this procedure intensively, it can be worth taking into consideration sexually transmitted disease:: set rather consequently.

2022-06-07 16:53:37

If you have an unsorted vector, after that you can merely exchange with the last vector component after that resize().

With a gotten container, you'll be ideal off with std::vector::erase(). Keep in mind that there is a std::remove() specified in <algorithm>, yet that does not in fact do the getting rid of. (Read the documents meticulously).

2022-06-07 16:52:49

Use the international method sexually transmitted disease:: remove with the begin and also end iterator, and afterwards make use of sexually transmitted disease:: vector.erase to in fact remove the components.

Documents links¢ sexually transmitted disease:: remove¢ sexually transmitted disease:: vector.erase

std::vector<int> v;

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2

Thanks to Jim Buck for mentioning my mistake.

2022-06-07 16:19:26

std::remove does not in fact get rid of the component from the container, yet it does return the new end iterator which can be passed to container_type::erase to do the REAL elimination of the added components that are currently at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
2022-06-07 16:17:50

See additionally std::remove_if to be able to make use of a predicate

Here is the instance from the link over:

vector<int> V;

copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
    // The output is "1 4 2 8 5 7"

vector<int>::iterator new_end = 
    remove_if(V.begin(), V.end(), 
              compose1(bind2nd(equal_to<int>(), 0),
                       bind2nd(modulus<int>(), 2)));
V.erase(new_end, V.end()); [1]

copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
    // The output is "1 5 7".
2022-06-07 16:17:02