c++ - unordered_map 未正确更新

标签 c++ segmentation-fault unordered-map

尝试使用以下代码片段将无序映射更新为只有小写字母,但它似乎在删除一个键值对后停止 { [33 '!']: 3 } 并退出循环,剩下的未访问 map 并打印部分更新的 map 。

 for (auto &i : m)
        if (!(i.first >= 'a' && i.first <= 'z'))
            m.erase(i.first);

下面的调试图片揭示了上面的内容

enter image description here

enter image description here

完整代码如下:

#include <iostream>
#include <unordered_map>
#include <algorithm>    
using namespace std;
int main()
{
    string line = "Try! Try! Try! until you succeed";
    //getline(cin, line);
    unordered_map<char, int> m;
    for (int i = 0; line[i]; i++)
    {   
        char lower = (char)tolower(line[i]);
        if (m.find(lower) == m.end())
            m.insert(make_pair(lower, 1));
        else
            m[lower]++;
    }

    for (auto &i : m) //only updates until ! 
        if (!(i.first >= 'a' && i.first <= 'z'))
            m.erase(i.first);

    cout<<"The freq. map so formed is : \n";
    for (auto &i : m)
        cout<<i.first<<"\t"<<i.second<<endl;
    
    return 0;
}
/*
OUTPUT : 
The freq. map so formed is : 
d       1
t       4
r       3
e       2
y       4
l       1
o       1
        5
n       1
u       3
i       1
s       1
c       2
*/

似乎无法理解为什么它不会遍历完整的无序 map 。

此外,不确定这是否有助于获得清晰的图片,但是,当使用标准 map 而不是无序 map 时,它会在同一实例中给出地址边界错误,其中 map 的下一个字符需要像这样更新:

enter image description here

enter image description here

最佳答案

您不能在以这种方式迭代时删除 map 的元素。当您删除迭代器时,它会失效,因此您需要在删除元素之前显式递增它。

试试这个代码:

 for (auto it = m.begin(); it != m.end();)
     if (!((*it).first >= 'a' && (*it).first <= 'z'))
         it = m.erase(it);
     else
        ++it;

关于c++ - unordered_map 未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69076861/

相关文章:

c++ - 如何将文件选择限制为单个目录?

c - int x = 时间(NULL); => 段错误?

macos - Snow Leopard 是否将核心转储放在特殊的地方?

c++ - unordered_map::find() 插入查找的键

c++ - 为什么 Gun *gun=&machinegun 有效,而 *gun=&machinegun 无效?

c++ - 如何在扩展的 PUB-SUB 模式中将发布者和订阅者与 C++ 中的 ZeroMQ 中的中介同步?

c++ - 在 C++20 中,析构函数中通常具有非 constexpr 行为的类的 constexpr 实例

c++ - map [] 运算符段错误

c++ - 具有多值的无序映射及其查找

c++ - 为 CString 创建 unordered_map 作为键