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?
clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.
The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
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());
Alternatively, change
a.erase(remove(a.begin(), a.end(), 1), a.end()); b.erase(remove(b.begin(), b.end(), 6), b.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With