Qt的QMap循环删除元素(erase),在运行时正常,在调试模式下报错,提供解决代码。
关键词:QMap、erase、迭代器、遍历与删除
问题描述:
在使用 Qt 的QMap容器时,尝试在遍历过程中删除元素,在循环中调用erase()方法,虽然程序在正常运行时可能不会立即出现异常,但在调试模式下,可能会遇到错误或未定义行为。
Qt版本:5.14.2
代码如下:
点击折叠或展开代码
void test_map_erase() |
{ |
QMap<int, int> map; |
// 插入10条数据 |
for (int i = 0; i < 10; ++i) { |
map.insert(i, i); |
} |
// 移除奇数 |
for(auto it=map.begin();it!=map.end();++it) |
{ |
if((it.key() % 2) == 1) { |
map.erase(it); |
} |
} |
qDebug() << map; |
} |
运行结果:
运行输出:
QMap((0, 0)(2, 2)(4, 4)(6, 6)(8, 8)) |
调试模式运行报错,如图:
修改后代码:
为避免运行和调试不一致,统一改为如下代码:
点击折叠或展开代码
void test_map_erase() |
{ |
QMap<int, int> map; |
// 插入10条数据 |
for (int i = 0; i < 10; ++i) { |
map.insert(i, i); |
} |
// 移除奇数 |
for(auto it=map.begin();it!=map.end();) |
{ |
if((it.key() % 2) == 1) { |
it = map.erase(it); |
} else { |
++it; |
} |
} |
qDebug() << map; |
} |
注意:
- for循环去掉++it:
for(auto it=map.begin();it!=map.end(); )