multiset 用法 及multimap 同一个key多个value用法
头文件
#include <set>
代码
#include <set>
#include <iostream>
using namespace std;
int main() {
multiset <int> ms;
ms.insert(1);
ms.insert(5);
ms.insert(5);
ms.insert(5);
ms.insert(2);
ms.insert(1);
for (auto iter = ms.begin(); iter != ms.end(); iter++){
cout << *iter << endl;
}
cout << "end" << endl;
auto iter = ms.find(5);
cout << *iter << endl;
ms.erase(iter);
cout << "end" << endl;
int num = ms.count(5);
cout << "find 5 num is " << num << endl;
cout << "end" << endl;
for (auto iter = ms.begin(); iter != ms.end(); iter++){
cout << *iter << endl;
}
return 0;
};
输出
1
1
2
5
5
5
end
5
end
find 5 num is2
end
1
1
2
5
5
multimap 同一个key多个value用法
在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)
#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
cout << "solution 1" << endl;
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
cout << "solution 1" << endl;
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
cout << "solution 1" << endl;
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;
}
solution 1
中国--50
中国--55
中国--60
solution 1
美国--30
美国--20
美国--10
solution 1
中国--50
中国--55
中国--60
资料:
https://blog.csdn.net/culing2941/article/details/108617870
https://blog.csdn.net/u013427969/article/details/52675992
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通