在multimap中,同一个键关联的元素必然相邻存放。基于这个事实,就可以将某个键对应的值一一输出。
1、使用find和count函数。count函数求出某个键出现的次数,find函数返回一个迭代器,指向第一个拥有正在查找的键的实例。
2、使用lower_bound(key)和upper_bound(key)
lower_bound(key)返回一个迭代器,指向键不小于k的第一个元素
upper_bound(key)返回一个迭代器,指向键不大于k的第一个元素
3、使用equat_range(key)
返回一个迭代器的pair对象,first成员等价于lower_bound(key),second成员等价于upper_bound(key)
1 #include <iostream>
2 #include <string>
3 #include <map>
4 using namespace std;
5
6 int main()
7 {
8 multimap<string,int> m_map;
9 string s("中国"),s1("美国");
10 m_map.insert(make_pair(s,50));
11 m_map.insert(make_pair(s,55));
12 m_map.insert(make_pair(s,60));
13 m_map.insert(make_pair(s1,30));
14 m_map.insert(make_pair(s1,20));
15 m_map.insert(make_pair(s1,10));
16 //方式1
17 int k;
18 multimap<string,int>::iterator m;
19 m = m_map.find(s);
20 for(k = 0; k != m_map.count(s); k++,m++)
21 cout<<m->first<<"--"<<m->second<<endl;
22 //方式2
23 multimap<string,int>::iterator beg,end;
24 beg = m_map.lower_bound(s1);
25 end = m_map.upper_bound(s1);
26 for(m = beg; m != end; m++)
27 cout<<m->first<<"--"<<m->second<<endl;
28 //方式3
29 beg = m_map.equal_range(s).first;
30 end = m_map.equal_range(s).second;
31 for(m = beg; m != end; m++)
32 cout<<m->first<<"--"<<m->second<<endl;
33 return 0;
34 }
原文链接: https://www.cnblogs.com/lca1826/p/6847404.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/253843
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!