2012-08-30 79 views
0

我試圖運行此函數:地圖/套迭代器不derefrencable運行時錯誤

os::TMXTileset* os::TMXMap::getTilesetFromGid(int gid) 
    { 
     TMXTileset* tileset; 
     std::map<std::string, TMXTileset>::iterator it; 
     std::map<std::string, TMXTileset>::iterator comp; 

     for (it=tilesetMap.begin(); it != tilesetMap.end(); it++) 
     { 
      comp = it; 
      comp++; 
      if ((gid >= it->second.getFirstGid()) && (gid < comp->second.getFirstGid())) 
      { 
       return &it->second; 
      } 
     } 
     tileset = &it->second; 
     return tileset; 
    } 

..但它給我這個錯誤:

"map/set iterator not derefrencable"

我首先想到的是停止取消引用它(使用它 - >秒而不是(* it).second),但這並沒有改變任何東西。

任何想法?

回答

3

你先複製它,然後你提前複製,然後解除引用副本。這意味着,只要它在最後一個元素之前的元素上,就可以對end()進行解引用。

您可以在只有1個條目的地圖上輕鬆測試它 - 它總是無法解除引用comp。

,你應該這樣做:

TMXTileset* tileset; 
std::map<std::string, TMXTileset>::iterator it; 
std::map<std::string, TMXTileset>::iterator comp; 

for (it=tilesetMap.begin(); /*it != tilesetMap.end() can be ommited due to check for comp */; it++) 
{ 
    comp = it; 
    comp++; 
    if (comp == tilesetMap.end()) 
    { 
     break; 
    } 
    ... 
} 
+0

謝謝,那很完美。 我認爲end()指的是最後一個元素,這解釋了我的錯誤。 謝謝! – DormoTheNord

+1

考慮使用前增量(++ i)而不是後增量。特別是在迭代器的情況下,這可以更快。如果你不需要它,你還應該縮小它的範圍和比例。新的C++關鍵字auto對此非常有幫助。只需刪除它和comp的聲明,並在第一次使用之前放置一個auto。 (for(auto it = tilsetMap.begin()... and auto comp = it;) –

0

如果你的for循環沒有被中斷,你的for循環會超出地圖的末尾,所以你的倒數第三行將會失敗。

+0

沒有 - 它沒有。 for循環的設置是正確的。 –

+0

當然可以。當for == tilesetMap.end()時for循環停止,然後it-> second未定義。 – JohnB