关于地图 STL 的问题

problems about map STL

本文关键字:STL 问题 地图 于地图      更新时间:2023-10-16
void huffmanDecode(string str){
string temp;
map<string, char>::iterator it;
//for(auto iter=myMap.begin();iter!=myMap.end();++iter)
    //cout<<iter->first<<" "<<iter->second<<" "<<endl;
for (unsigned int i = 0; i < str.size(); i++)
{
    temp += str[i];
    it = myMap.find(temp);
    if (it == myMap.end())
        continue;
    else
    {
        cout<<it->first<<" ";//crashed here, "Thread 1:EXC_BAD_ACCESS(code=1,address=0x0)
        //cout << it->second << " ";
        temp = nullptr;
    }
}
}

我正在尝试通过地图解决霍夫曼解码问题,但它崩溃了~~~

std::string::operator= 有一个需要const char*的重载。这是当你说时使用的重载

temp = nullptr;

现在,要求是const char*指向以 null 结尾的字符串。因此,它不能是空指针。不允许传递空指针,并且允许实现在这种情况下引发异常。在任何情况下,尝试使用此类字符串都会导致未定义的行为std::string构造函数也有类似的情况。

如果您打算将temp重新设置为空字符串,则有以下几种选择:

temp = "";
temp.clear();
temp = std::string();

您已将temp定义为std::string,而不是指针。因此,将其设置为 nullptr 是错误的!

如果你想清除它的内容,我假设你真的想要,试试这个:

temp.clear();