C++:从映射中删除迭代器,然后递增到下一个迭代器
C++: Erasing an iterator from a map and then incrementing to the next iterator
此方法会导致中止错误:"map/set iterator not incrementable."
因此,在if
失败并且确定了应该擦除的有效迭代器之后(并且是),通过++_iter
继续到映射中的下一个迭代器失败,因为_iter
不再是有效的对象/指针。
迭代地图并能够删除整个地图中的单个项目的正确程序是什么?
typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;
\...
void BitmapCache::CleanCache() {
//Clean the cache of any NULL bitmaps that were deleted by caller.
for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ++_iter) {
if(_iter->second != NULL) {
if((_iter->second->w < 0 && _iter->second->h < 0) == false) continue;
}
_cache.erase(_iter);
}
}
您只需要稍微小心一点:
void BitmapCache::CleanCache() {
//Clean the cache of any NULL bitmaps that were deleted by caller.
for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
if(_iter->second != NULL) {
if((_iter->second->w < 0 && _iter->second->h < 0) == false)
{
++_iter;
continue;
}
}
_cache.erase(_iter++);
}
}
map::erase(iterator)
为您提供了一个迭代器,指向擦除后映射中的下一个元素(如果有的话)。因此,你可以做:
for(MapStrBmpIter _iter = _cache.begin(); _iter != _cache.end(); ) {
if(_iter->second != NULL) {
if((_iter->second->w < 0 && _iter->second->h < 0) == false) {
++_iter;
continue;
}
}
_iter = _cache.erase(_iter);
}
关联容器的标准擦除循环:
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
if (delete_condition)
{
m.erase(it++);
}
else
{
++it;
}
}
在迭代过程中安全擦除迭代器的规范方法是使用container::erase
:的结果
void BitmapCache::CleanCache() {
//Clean the cache of any NULL bitmaps that were deleted by caller.
MapStrBmpIter _iter = _cache.begin();
while (_iter != _cache.end()) {
bool erase_entry= true;
if(_iter->second != NULL) {
if((_iter->second->w < 0 && _iter->second->h < 0) == false)
erase_entry= false;
}
if (erase_entry)
_iter= _cache.erase(_iter);
else
++_iter;
}
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 如何返回引用,然后递增迭代器
- 从两端开始浏览列表,然后使用迭代器在中间停止
- 迭代器取消引用然后"."运算符对立。 "->"运算符
- 减少 begin() 迭代器,然后再次增加它
- 将迭代器存储在临时容器上,然后从其他容器中删除它们
- C++:从映射中删除迭代器,然后递增到下一个迭代器
- 是否可以保存std::list中新插入元素的迭代器,然后使用该迭代器安全地擦除该元素?