auto& kphist = this->kphist;
for (auto& it : kphist) {
it.second.aging(); // EXC-BAD-ACCESS
if(it.second.age > LAST_DAY){
kphist.erase(it.first);
continue;
}
}
kphist 是私有(private)成员(member)
Class A{
private:
unordered_map<int, KeyPointHistory> kphist;
}
调试器显示 kphist 中的所有项目都是有效的,怎么可能在 for 循环中有错误的引用。什么可能会出错?
来自 cppreference.com for std::unordered_map::erase()
: 对已删除元素的引用和迭代器无效。其他迭代器和引用不会失效。 因此,您不能在 for 循环范围内使用 std::unordered_map::erase()
(因为这将尝试递增无效迭代器) .
为了避免递增一个无效的迭代器,你可以简单地先递增
然后使用原始迭代器删除:
for(auto i=map.begin(),end=map.end(); i!=end; ) { // no increment here
auto it=i++; // but here instead
if(must_remove(it))
map.erase(it);
}
事实上,由于 erase()
将迭代器返回到下一个元素,您可以避免额外的迭代器 it
(感谢 Hurkyl 在评论中指出这一点):
for(auto i=map.begin(),end=map.end(); i!=end; ) { // no increment here
if(must_remove(i))
i = map.erase(i); // but here
else
++i; // or here instead
}
无需制作要删除的元素的键列表...
顺便说一句,你为什么不使用 std::map
(而不是 std::unordered_map
),因为你的键是 int
(很容易订购)?另外,为什么要对同名成员变量进行引用kphist
?