在 stdmap 或 stdmultimap 中搜尋
有幾種方法可以在 std::map 或 std::multimap 中搜尋金鑰。
-
要獲取第一次出現的鍵的迭代器,可以使用
find()函式。如果金鑰不存在,則返回end()。std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; auto it = mmp.find(6); if(it!=mmp.end()) std::cout << it->first << ", " << it->second << std::endl; //prints: 6, 5 else std::cout << "Value does not exist!" << std::endl; it = mmp.find(66); if(it!=mmp.end()) std::cout << it->first << ", " << it->second << std::endl; else std::cout << "Value does not exist!" << std::endl; // This line would be executed. -
查詢
std::map或std::multimap中是否存在條目的另一種方法是使用count()函式,該函式計算與給定鍵關聯的值的數量。由於std::map僅將每個鍵與一個值相關聯,因此其count()函式只能返回 0(如果鍵不存在)或 1(如果存在)。對於std::multimap,count()可以返回大於 1 的值,因為可能有多個值與同一個鍵相關聯。std::map< int , int > mp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} }; if(mp.count(3) > 0) // 3 exists as a key in map std::cout << "The key exists!" << std::endl; // This line would be executed. else std::cout << "The key does not exist!" << std::endl;如果你只關心某個元素是否存在,
find肯定更好:它記錄你的意圖,對於multimaps,它可以在找到第一個匹配元素後停止。 -
在
std::multimap的情況下,可能有幾個元素具有相同的鍵。為了得到這個範圍,使用equal_range()函式,它返回分別具有迭代器下界(包括)和上界(不包括)的std::pair。如果金鑰不存在,則兩個迭代器都將指向end()。auto eqr = mmp.equal_range(6); auto st = eqr.first, en = eqr.second; for(auto it = st; it != en; ++it){ std::cout << it->first << ", " << it->second << std::endl; } // prints: 6, 5 // 6, 7