2012-05-16 100 views
0

我有我的程序下面的方法。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 

謝謝! :)

+0

如果'地圖::找到()'找不到容器中的元素,它返回一個迭代器,一個過去的最後一個元素,即:'地圖::結束()',這是你做了什麼,因爲輸出是'錯誤'。你對find()返回的內容感到困惑嗎?從Q中發佈的代碼和輸出中,似乎元素確實被刪除。 –

+0

你是什麼意思,它不被刪除?它看起來像我。 – juanchopanza

+0

如果'it ++'給你'indexMap.end()'會怎麼樣?解除引用會導致UB。 –

回答

4

此塊:

map<int,obj>::iterator iter = this->indexMap.find(id); 
if(iter == this->indexMap.end()) 
{ 
    cout << "ERROR" << endl; 
} 

打印出ERROR如果與鍵id的元件未在圖中找到。因此它已被刪除。

+0

Omg謝謝!做出錯誤,一定是睡眠不足 – mister

+1

的@dupdupdup沒問題,我知道這種感覺。你可能想接受答案,以便其他人不浪費時間思考你的問題仍然沒有答案。 – juanchopanza

+0

對不起,我昨天接受了答案,但不知道爲什麼它被取消,可能是由於延遲問題。無論如何感謝 – mister