2010-09-04 74 views
1

我正在使用multimap stl,我迭代了我的地圖,我沒有在地圖內找到想要的對象,現在我想檢查一下我的迭代器是否持有這個東西想要或沒有,我有困難,因爲它不是零或什麼的。感謝名單!如何檢查我的迭代器是否沒有任何東西

+0

是否等於map.end()? map.end()是過去的最後一個索引,因此技術上不在枚舉內 – 2010-09-04 21:07:26

回答

8

如果它找不到你想要的東西,那麼它應該等於容器的end()方法返回的迭代器。

所以:

iterator it = container.find(something); 
if (it == container.end()) 
{ 
    //not found 
    return; 
} 
//else found 
0

爲什麼你遍歷你的地圖上找到的東西,你應該去喜歡ChrisW找到地圖的關鍵...

嗯,你想找到在你的地圖中的價值,而不是關鍵?那麼你應該這樣做:

map<int, string> myMap; 
myMap[1] = "one"; myMap[2] = "two"; // etc. 

// Now let's search for the "two" value 
map<int, string>::iterator it; 
for(it = myMap.begin(); it != myMap.end(); ++ it) { 
    if (it->second == "two") { 
     // we found it, it's over!!! (you could also deal with the founded value here) 
     break; 
    } 
} 
// now we test if we found it 
if (it != myMap.end()) { 
    // you also could put some code to deal with the value you founded here, 
    // the value is in "it->second" and the key is in "it->first" 
} 
相關問題