关于地图STL的问题

时间:2014-11-05 09:03:37

标签: c++ map stl

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;
    }
}
}

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

2 个答案:

答案 0 :(得分:3)

std::string::operator=有一个需要const char*的重载。这是您说

时使用的重载
temp = nullptr;

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

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

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

答案 1 :(得分:2)

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

如果你想清除它的内容,我认为你真的想要这样做,试试这个:

temp.clear();