I understand there is erase-remove idiom for c++. And the remove
method under <algorithm>
will move target elements to the back of the range.
However, the output below is confusing to me.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {10, 20, 30, 20, 30, 20, 10, 10, 20};
auto pend = remove(vec.begin(), vec.end(), 20);
cout << "After removing 20: " << endl;
for (const auto& x : vec) {
cout << x << " ";
}
cout << endl;
cout << "use pend: " << endl;
for (auto p = vec.begin(); p != pend; p++) {
cout << " " << *p;
}
cout << endl;
return 0;
}
The output is:
After removing 20:
10 30 30 10 10 20 10 10 20
use pend:
10 30 30 10 10
There are two questions here:
For "After removing 20", why are there 10 mixed with 20 at the back?
10 30 30 10 10 20 10 10 20
For "use pend:", why does it fail to print the last two more 10's? There are five 10's in the original vector, and 10's are not supposed to be removed?
From the library, remove() method returns the iterator pend
template
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
An iterator to the element that follows the last element not removed.
The range between first and this iterator includes all the elements in the sequence that do not compare equal to val.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…