#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 7.7.1 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 b should be a=2,3,7,5,4 and b=7,4,3,3,1,7.
What's happening here?
{2,3,7,5,4};
? – Falconiform2,3,7,5,4
(both1
s get removed)? I believe you're violating some precondition by passing a reference to a member of thevector
you're iterating over. Both lines can be fixed by making a copy -+a[0]
and+b[0]
– Keiko+
for this bordering on obfuscation? (In theory,int(a[0])
should also work; the result is an rvalue, and using it to initialize a reference shouldn't result in an alias to any existing value, anywhere. I don't know if I'd feel comfortable counting on a compiler not optimizing this, however. And it's not really more explicit either; the lvalue-rvalue distinction is often very subtle.) – Eudy+
andint(a[0])
fall into the same obfuscation bucket and I'd cry foul if I saw code like that in a review for instance. But when posting a comment on SO ... fewer keystrokes FTW :) If I were posting an answer instead I'd have stored the value in a temp variable as shown below. – Keikoreturn 1
instead of0
? – Kirbie