C++ STL - map的使用
输出带空格格式
控制格式,输出格式:1 2 3 4 5(中间有空格,末尾无空格):
auto it=mp.begin();
cout<<it->second;
while(++it!=mp.end())
cout<<" "<<it->second;
输出首尾元素
输出map中最后一个元素和第一个元素:
map<string,int>mp1; //姓名 分数
map<string,string>mp2; // 姓名 学号
// 输出最后一个元素
auto it1=mp1.rbegin(); // 不能用end,会没有输出
string s1=it1->first;
cout<<s1<<" "<<mp2[s1]<<endl;
// 输出第一个元素
auto it2=mp1.begin();
string s2=it2->first;
cout<<s2<<" "<<mp2[s2]<<endl;
正序遍历所有元素
三种写法:
// 定义map类型
map<int,int>mp;
....
// 定义迭代器 写法1
map<int, int>::iterator iter = mp.begin();
while (iter!=map1.end())
{
cout << iter->first << "***" << iter->second << endl;
iter++;
}
// 定义迭代器 写法2
map<int, int>::iterator iter;
for (iter = mp.begin(); iter != mp.end(); iter++)
cout << iter->first << "***" << iter->second << endl;
// 定义迭代器 写法3
// 或者使用 C++11 auto关键字 自动识别map类型
for (auto iter = mp.begin(); iter != mp.end(); iter++)
cout << iter->first << "***" << iter->second << endl;
倒序遍历所有元素
// 定义map类型
map<int,int>mp;
....
// 定义迭代器
map<int, int>::reverse_iterator iter;
for (iter = mp.rbegin(); iter != mp.rend(); iter++)
cout << iter->first << "***" << iter->second << endl;
count函数
语法:mp.count(需要查找的元素key)
,存在返回1,不存在返回0。(判断map中key是否存在)
map<int,int> mp;
for(int i=0;i<n;i++)
{
if(mp.count(a[i])) ...
}
find函数
使用find,返回的是被查找元素的位置,没有则返回map.end()
语法:mp.find(需要查找的元素key)
,存在则返回元素下标,否则返回 map.end()
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2020-03-07 寒假Day44:JAVA-异常处理
2020-03-07 寒假Day44:bfs