在multimap中,同一个键关联的元素必然相邻存放。基于这个事实,就可以将某个键对应的值一一输出。
1、使用find和count函数。count函数求出某个键出现的次数,find函数返回一个迭代器,指向第一个拥有正在查找的键的实例。
2、使用lower_bound(key)和upper_bound(key)
lower_bound(key)返回一个迭代器,指向键不小于k的第一个元素
upper_bound(key)返回一个迭代器,指向键大于k的第一个元素
就相当于通常情况下遍历容器时的begin和end一样。
3、使用equat_range(key)
返回一个迭代器的pair对象,first成员等价于lower_bound(key),second成员等价于upper_bound(key)
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
multimap<string,int> m_map;
string s(\"中国\"),s1(\"美国\");
m_map.insert(make_pair(s,50));
m_map.insert(make_pair(s,55));
m_map.insert(make_pair(s,60));
m_map.insert(make_pair(s1,30));
m_map.insert(make_pair(s1,20));
m_map.insert(make_pair(s1,10));
//方式1
int k;
multimap<string,int>::iterator m;
m = m_map.find(s);
for(k = 0;k != m_map.count(s);k++,m++)
cout<<m->first<<\"--\"<<m->second<<endl;
//方式2
multimap<string,int>::iterator beg,end;
beg = m_map.lower_bound(s1);
end = m_map.upper_bound(s1);
for(m = beg;m != end;m++)
cout<<m->first<<\"--\"<<m->second<<endl;
//方式3
beg = m_map.equal_range(s).first;
end = m_map.equal_range(s).second;
for(m = beg;m != end;m++)
cout<<m->first<<\"--\"<<m->second<<endl;
return 0;
}
转载自:https://zhidao.baidu.com/question/918049459459983899.html,作者:龍__鳳
继续阅读与本文标签相同的文章
上一篇 :
智特医疗创始人张欣博士出席2019携程投资峰会
-
汇编(五)栈、CPU提供的栈机制、push、pop指令
2026-05-18栏目: 教程
-
为什么绝大部分公司用钉钉上班不用微信,其实原因很简单
2026-05-18栏目: 教程
-
谷歌证实Pixel 4不支持Daydream,VR头显盒子也将停售
2026-05-18栏目: 教程
-
图解:抛弃IDE使用编译器亲手编译C
2026-05-18栏目: 教程
-
最新测试证明:无人驾驶技术还需加强安全性和稳定性
2026-05-18栏目: 教程
