什么是map函数
定义:map<键值,实值>mp
按照键值自动升序排序,可以根据键值快速找到实值。
头文件
#include<map>
map插入赋值和遍历输出
这个输出的时候用mp.first或者mp->first都可以。
如果用'."过不了,可以换成"->试试。
#include<iostream>
#include<map>
using namespace std;
map<int,int>mp1;
map<string,string>mp2;
int main()
{
//插入赋值
mp1.insert({1,3});
mp1.insert({2,2});
mp1.insert({3,1});
mp2.insert({"1234","哈哈哈哈"});
mp2.insert({"12345","哈哈哈哈哈"});
mp2.insert({"123456","哈哈哈哈哈哈"});
//遍历
for(auto it:mp1)
cout<<it.first<<' '<<it.second<<endl;
cout<<"---------------\n";
for(auto it:mp2)
cout<<it.first<<' '<<it.second<<endl;
}
find查找
这个就是需要用到iterator(迭代器)来定义s1,s2,s3。这个我也不知道为啥输出的时候用".”不对。
#include<iostream>
#include<map>
using namespace std;
map<string,string>mp2;
int main()
{
mp2.insert({"1234","哈哈哈哈"});
mp2.insert({"12345","哈哈哈哈哈"});
mp2.insert({"123456","哈哈哈哈哈哈"});
map<string,string>::iterator s1,s2,s3;//iterator(迭代器)
s1=mp2.find("1234");
s2=mp2.find("12345");
s3=mp2.find("123456");
cout<<s1->first<<' '<<s1->second<<endl;
cout<<s2->first<<' '<<s2->second<<endl;
cout<<s3->first<<' '<<s3->second<<endl;
}
例题参考
1.牛客周赛 Round 1题解的B题