我有我的程序下面的方法。STL地圖不會刪除
奇怪的是之後我打電話擦除的數據不會被刪除。
有什麼想法?
map<int,obj>::iterator it = this->indexMap.find(id);
if(it != this->indexMap.end())
{
int mapSize = this->indexMap.size();
int dataSize = (*it).second.getDataMap().size();
//copy data to another node | even when it doesn't get into this if condition, it does not remove the data
if(mapSize> 1 && dataSize != 0)
{
it++;
this->copyData(id,it->first);
it--;
}
//remove peer | i've tried id and it, both does not work
this->indexMap.erase(it);
map<int,obj>::iterator iter = this->indexMap.find(id);
if(iter == this->indexMap.end())
{
cout << "ERROR" << endl;
}
}
輸出:
ERROR
謝謝! :)
如果'地圖::找到()'找不到容器中的元素,它返回一個迭代器,一個過去的最後一個元素,即:'地圖::結束()',這是你做了什麼,因爲輸出是'錯誤'。你對find()返回的內容感到困惑嗎?從Q中發佈的代碼和輸出中,似乎元素確實被刪除。 –
你是什麼意思,它不被刪除?它看起來像我。 – juanchopanza
如果'it ++'給你'indexMap.end()'會怎麼樣?解除引用會導致UB。 –