I came up with a program
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> a = {1,2,3,7,1,5,4};
vector<int> b = {6,7,4,3,3,1,7};
a.erase(remove(a.begin(),a.end(),a[0]),a.end());
b.erase(remove(b.begin(),b.end(),b[0]),b.end());
return 1;
}
For this specific example, my GNU gdb Ubuntu states that at return 1
line: a = {2,3,7,1,5,4}
which is not expected (only deletes one 1
), and b = {7,4,3,3,1}
which is not expected.
My expectation is a
and b
should be a=2,3,7,5,4
and b=7,4,3,3,1,7
.
What's going on here?
std::remove
takes the third argument by reference and it invalidates references into the range it works on (in the sense that it shifts stuff around and thus changes values of elements in the range). The problem is that you change a[0]
, the reference argument, during the call, which you must not do.
To fix this, pass a copy instead:
a.erase(remove(a.begin(),a.end(),int{a[0]}),a.end());