[英]unordered_multimap - iterating the result of find() yields elements with different value
C ++中的multimap看起來很奇怪,我想知道為什么
#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
當我明確要求'a'時,為什么輸出仍然包含b作為鍵的任何內容? 這是編譯器還是stl錯誤?
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;
}
這不是一個錯誤,它是設計的。 find
返回一個匹配元素的迭代器,就是全部。 您將使用構造迭代到地圖的末尾。
您需要使用multimap::equal_range
來執行您所需的操作。
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/
看起來你會在一對完整的“列表”中得到一個迭代器,從第一對開始,用'a'作為關鍵。 因此,當你迭代到最后時,你自然會得到超越'a'的所有東西。 如果你想要'c',你可能會在整個“列表”中迭代你做的事情。 也許你應該迭代到“它!= map.end()&& it-> first =='a'”如果你想要所有的a。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.