当前位置: 首页 > news >正文

c++ - 在循环中使用迭代器删除 unordered_set 中的元素

标签 c++ unordered-set

请考虑以下代码:

Class MyClass 为自定义类:class MyClass
{
public:MyClass(int v) : Val(v) {}int Val;
};

然后下面的代码将在调用 it = T.erase(it); 之后在循环中导致 Debug Assertion Failed:

unordered_set<MyClass*> T;
unordered_set<MyClass*>::iterator it;for (int i=0; i<10; i++)T.insert(new MyClass(i));for (it = T.begin(); it != T.end(); it++)
{if ( (*it)->Val == 5 )it = T.erase(it); // After this line executes, in the next loop, the error occurs.
}

如何解决,为什么? PS:我的环境:VS2010

最佳答案:

假设最后一个元素的 Val = 5。
it = T.erase(it) 被调用,it 被设置为 T.end()。
然后 it++ 被调用,这会导致错误,因为 it 已经设置为结束。
本质上…当您删除当前代码中的一个元素时,您最终会双倍推进迭代器。

你可以改用这样的东西:

for (it = T.begin(); it != T.end(); (*it)->Val == 5? it = T.erase(it) : ++it);

我通常是这样做的:

for (auto it = T.begin(); it != T.end(); )
{if ((*it)->value == 5) it = T.erase(it);else ++it;
}

如果擦除条件变得更复杂,这可能会提高可读性。

关于c++ - 在循环中使用迭代器删除 unordered_set 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252386/

http://www.lryc.cn/news/346808.html

相关文章:

  • 深入了解哈希映射(HashMap)
  • Public Key Retrieval is not allowed
  • iphone进入恢复模式怎么退出?分享2种退出办法!
  • Leetcode 107:二叉树的层次遍历II
  • LNMP一键安装包
  • [机器学习-05] Scikit-Learn机器学习工具包进阶指南:协方差估计和交叉分解功能实战【2024最新】
  • 多线程的情况下 AopContext.currentProxy()切面代理失效问题
  • https://是怎么实现的?
  • Linux无root配置Node,安装nvm
  • 蛋糕店做配送小程序的作用是什么
  • 重写muduo之TcpServer
  • 腾讯云服务器之ssh远程连接登录及转发映射端口实现内网穿透(实现服务器访问本地电脑端口)
  • oracle 9i 行头带有scn的表
  • MySql#MySql安装和配置
  • WEB前端复习——HTML
  • Java医院绩效管理应用系统源码java+ maven+ avue 公立医院绩效考核管理系统源码 支持二开
  • 湖南知识付费系统开发公司,教育机构如何提高转化率?有哪些途径?
  • Goland GC
  • 【SRC实战】合成类小游戏外挂漏洞
  • 【牛客】SQL206 获取每个部门中当前员工薪水最高的相关信息
  • 2024年最新趋势跨境电商平台开发需了解的新技术
  • Mac 查看jdk版本
  • C++面向对象学习笔记五
  • 7-Zip 的使用技巧
  • 德国储能项目锂电池储能集装箱突发火灾:安全挑战再引关注
  • FFmpeg常用API与示例(二)—— 解封装与转封装
  • 笨方法自学python(一)
  • centos7.9升级4.19内核
  • 神经网络模型与前向传播函数
  • 跟我学C++中级篇——内联补遗