假设我们有以下内容:
struct IsEven {
bool operator() (int i) { return i % 2 == 0; }
};
然后:
vector<int> V; // fill with ints
vector<int>::iterator new_end = remove_if(V.begin(), V.end(), IsEven());
V.erase(new_end, V.end());
这段代码运行正常(它只留下奇数整数V
)。但是似乎从new_end
到V.end()
的元素并不是我们要删除的偶数整数。例如,如果v
最初为1 4 2 8 5 7
,那么我得到的是这些元素的8 5 7
(尽管在erase
调用后,vector确实只剩下1 5 7
)。
显然,(根据http://www.sgi.com/tech/stl/remove_if.html)
The iterators in the range [new_last, last) are all still dereferenceable,
but the elements that they point to are unspecified.
首先,什么鬼?其次,我如何避免重新实现
remove_if
而解决这个问题?