0

I'm trying to remove all instances of certain values from a vector, however when there are only one or two instances of the same value, one instance of the value remains:

//Removing any values in arr that match the values in copies
vector<int> arr = {100,100,50,40,40,20,10};
vector<int> copies = {100,40};

for(int i = 0; i < copies.size(); i++)
    {
        vector<int>::iterator j = find(arr.begin(), arr.end(), copies[i]);
        arr.erase(j);
    }

With this code, arr returns as {100,50,40,20,10} but if there are three or more instances of these values, .erase will remove them all

If anybody could explain why having one or two of the same value will save one from being erased I would greatly appreciate it.

BDBradley
  • 1
  • 1
  • 2
    `std::find` only finds one possible iterator that contains the specified element. To find and remove all elements that you want, use `std::remove_if`. – Telescope Nov 22 '20 at 23:52
  • 2
    Does this answer your question? [Erasing elements from a vector](https://stackoverflow.com/questions/347441/erasing-elements-from-a-vector) – Michał Kaczorowski Nov 23 '20 at 00:00
  • *"but if there are three or more instances of these values, `.erase` will remove them all"* -- this is not what I am seeing. I tried your code after changing the initialization of `arr` to `{100,100,100,50,40,40,40,20,10}` and the result was `100 100 50 40 40 20 10`. Only one `100` and one `40` was removed, not all of them. – JaMiT Nov 23 '20 at 02:17

0 Answers0