我是陈姐 發表於 2025-7-14 15:23:00

Qt问题记录002:QMap的erase陷阱,正常运行与调试模式结果不同

<br>
<p>摘要:<br>
    Qt的QMap循环删除元素(erase),在运行时正常,在调试模式下报错,提供解决代码。<br>
<br></p>
<p>关键词:<br>
    <code>QMap</code>、<code>erase</code>、迭代器、遍历与删除<br>
<br></p>
<h4 id="问题描述">问题描述:</h4>
<p>在使用 Qt 的<code> QMap</code> 容器时,尝试在遍历过程中删除元素,在循环中调用 <code>erase()</code> 方法,虽然程序在正常运行时可能不会立即出现异常,但在调试模式下,可能会遇到错误或未定义行为。</p>
<p>Qt版本:5.14.2<br>
<br></p>
<h4 id="代码如下">代码如下:</h4>
<details open=""><summary>点击折叠或展开代码</summary>
<pre><code class="language-C++">void test_map_erase()
{
    QMap&lt;int, int&gt; map;
    // 插入10条数据
    for (int i = 0; i &lt; 10; ++i) {
      map.insert(i, i);
    }
    // 移除奇数
    for(auto it=map.begin();it!=map.end();++it)
    {
      if((it.key() % 2) == 1) {
            map.erase(it);
      }
    }
    qDebug() &lt;&lt; map;
}
</code></pre>
</details>
<br>
<h4 id="运行结果">运行结果:</h4>
<p>运行输出:</p>
<pre><code>QMap((0, 0)(2, 2)(4, 4)(6, 6)(8, 8))
</code></pre>
<br>
<p>调试模式运行报错,如图:<br>
<img src="https://img2024.cnblogs.com/blog/2951860/202507/2951860-20250714143149578-1221908558.png" alt="image" loading="lazy"><br>
<br></p>
<h4 id="修改后代码">修改后代码:</h4>
<p>为避免运行和调试不一致,统一改为如下代码:</p>
<details open=""><summary>点击折叠或展开代码</summary>
<pre><code class="language-C++">void test_map_erase()
{
    QMap&lt;int, int&gt; map;
    // 插入10条数据
    for (int i = 0; i &lt; 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() &lt;&lt; map;
}
</code></pre>
</details>
<br>
<p>注意:</p>
<ol>
<li>for循环去掉++it:<code>for(auto it=map.begin();it!=map.end(); )</code></li>
<li>满足情况移除时:<code>it = map.erase(it);</code></li>
<li>其他情况不移除时:<code>++it;</code></li>
</ol>
<br>
<h4 id="参考文献">参考文献:</h4>
<ul>
<li>Qt::QMap在for循环中使用erase的用法注意</li>
<li>QMap 的增删改查</li>
</ul>


</div>
<div id="MySignature" role="contentinfo">
    <br>
<br>
<p>作者:薄暮知秋</p>
<p>本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/wsry/p/18983862</p><br><br>
来源:https://www.cnblogs.com/wsry/p/18983862
頁: [1]
查看完整版本: Qt问题记录002:QMap的erase陷阱,正常运行与调试模式结果不同