我正在练习LeetCode中的简单问题。我想使用lambda从向量中删除元素(第一次这样做,感觉很不错)。但是我得到了一个负指针new_end。
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional> // std::greater
using namespace std;
int main()
{
vector<int> a = { 2, 7, 11, 15 };
int target = 9;
auto new_end = std::remove_if(a.begin(), a.end(), [&a, target](const int x)
{
return std::count(a.begin(), a.end(), x) > target;
});
a.erase(new_end, a.end());
return 0;
}
没有出现错误,但new_end是一个负指针值。
new_end
是否等于end
?看起来应该是这样的。 - NathanOliveriterator::end
没有指向有用的数据。它仅用于确定集合的结尾。 - Vinznew_end
的值看起来合理。我关心的一件事是在“remove_if”的谓词中使用了count(a.begin(),a.end(),x)
。一旦一个元素被“remove”,下一次调用谓词将通过超过new_end
访问已删除的值。已删除的元素具有未指定的值。 - Sean Cline