【发布时间】:2009-01-25 07:37:01
【问题描述】:
假设我们有:
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 调用之后,向量确实有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.
首先,WTF?其次,如何在不重新实现remove_if 的情况下解决这个问题?
【问题讨论】:
-
如果您使用指针容器的相关提示 - 如果您想使用指针删除,请使用分区:ddj.com/architect/184401414