2012-01-28 46 views
10

在C++中的多重映射看起來工作非常奇怪的,我想知道爲什麼unordered_multimap - 迭代的find()的結果產生不同的價值元素

#include <iostream> 
#include <unordered_map> 

using namespace std; 

typedef unordered_multimap<char,int> MyMap; 

int main(int argc, char **argv) 
{ 
    MyMap map; 
    map.insert(MyMap::value_type('a', 1)); 
    map.insert(MyMap::value_type('b', 2)); 
    map.insert(MyMap::value_type('c', 3)); 
    map.insert(MyMap::value_type('d', 4)); 
    map.insert(MyMap::value_type('a', 7)); 
    map.insert(MyMap::value_type('b', 18)); 

    for(auto it = map.begin(); it != map.end(); it++) { 
     cout << it->first << '\t'; 
     cout << it->second << endl; 
    } 

    cout << "all values to a" << endl; 
    for(auto it = map.find('a'); it != map.end(); it++) { 
     cout << it->first << '\t' << it->second << endl; 
    } 

} 

這是輸出:

c 3 
d 4 
a 1 
a 7 
b 2 
b 18 
all values to a 
a 1 
a 7 
b 2 
b 18 

爲什麼輸出仍然包含任何與b作爲關鍵時,我明確要求'一個'?這是一個編譯器或STL錯誤?

回答

36

find,作爲實現,返回第一個元素的迭代器,該元素與multimap中的鍵匹配(與任何其他映射一樣)。你很可能會尋找equal_range

// Finds a range containing all elements whose key is k. 
// pair<iterator, iterator> equal_range(const key_type& k) 
auto its = map.equal_range('a'); 
for (auto it = its.first; it != its.second; ++it) { 
    cout << it->first << '\t' << it->second << endl; 
} 
+0

如果更改 - >到。那麼我會接受你的答案。 – Arne 2012-01-28 16:58:41

+1

我有' - >'快樂。 – user7116 2012-01-28 17:04:05

-1

這似乎是你得到一個迭代器對的完整的「名單」,從第一個對與「A」,因爲它是關鍵。所以當你迭代到最後時,你自然會得到'a'以外的所有東西。如果你尋求'c',你可能會遍歷整個「列表」,做你在那裏做的事情。也許你應該迭代「it!= map.end()& & it-> first =='a'」如果你想要所有的a。

8

這不是一個錯誤,它是由設計。 find將迭代器返回到其中一個匹配元素,就是這樣。你會用你的構造迭代到地圖的末尾。

你需要使用multimap::equal_range來做你以後的事情。

4

www.cplusplus.com有一個例子,關於如何使用equal_range方法來獲取所有具有相同鍵的元素。

// unordered_multimap::equal_range 
#include <iostream> 
#include <string> 
#include <unordered_map> 
#include <algorithm> 

typedef std::unordered_multimap<std::string,std::string> stringmap; 

int main() 
{ 
    stringmap myumm = { 
    {"orange","FL"}, 
    {"strawberry","LA"}, 
    {"strawberry","OK"}, 
    {"pumpkin","NH"} 
    }; 

    std::cout << "Entries with strawberry:"; 
    auto range = myumm.equal_range("strawberry"); 
    for_each (
    range.first, 
    range.second, 
    [](stringmap::value_type& x){std::cout << " " << x.second;} 
); 

    return 0; 
} 

請參考鏈接:http://www.cplusplus.com/reference/unordered_map/unordered_multimap/equal_range/

+0

@einpoklum這是刪除之前的**答案**請閱讀這篇文章[你在做什麼錯了 - 在低質量崗位隊列中的理智 - ](http:///meta.stackoverflow.com/questions/287563/youre-doing-it-wrong-a-plea-for-sanity-in-the-low-quality-posts-queue) – 2016-03-26 17:25:25

+0

讓我改述一下(審查機制並沒有「不要讓你提出具體的評論,你可以從列表中選擇):OP問:「爲什麼X會發生?」 - 你的答案雖然可能在一般情況下有用,但並不能解釋OP代碼會發生什麼情況。所以,不是一個答案。 – einpoklum 2016-03-26 17:56:49

相關問題