Arn*_*rne 15 c++ iteration stl unordered-map c++11
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
c 3
d 4
a 1
a 7
b 2
b 18
all values to a
a 1
a 7
b 2
b 18
Run Code Online (Sandbox Code Playgroud)
当我明确要求'a'时,为什么输出仍然包含b作为键的任何内容?这是编译器还是stl错误?
use*_*116 51
find,如实现的那样,返回第一个元素的迭代器,该元素与多图中的键匹配(与任何其他映射一样).您可能正在寻找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;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
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;
}
Run Code Online (Sandbox Code Playgroud)
请参考链接:http : //www.cplusplus.com/reference/unordered_map/unordered_multimap/equal_range/
| 归档时间: |
|
| 查看次数: |
18150 次 |
| 最近记录: |