STLmap
$ Latex $ 懒得修
map
map,中文名映射
使用方法: map<key(键),value(值)>
key不可以重复,value可以重复
map容器按照key进行自动排序
map基础用法↓
#include <bits/stdc++.h>
using namespace std;
int main(){
map<char,int> mp;
//赋值方式1:数组形式进行赋值
mp['a']=123;
mp['b']=234;
mp['c']=345;
mp['d']=456;
cout<<"mp['a']="<<mp['a']<<endl;
mp['a']=111;//这种赋值方式相同下标会直接覆盖
//赋值方式2:insert()
//mp.insert('b',666) 错误写法,没有形成一对
mp.insert(pair<char,int>('e',666));//形成一对
mp.insert(pair<char,int>('e',999));//不会完成相同下标的覆盖
//使用迭代器进行for循环
//iterator 指针-->begin(),end()等
map<char,int>::iterator it;//定义迭代器,用auto可以不写
//输出方式1
for(/*用auto直接写auto*/it=mp.begin();it!=mp.end();it++){
// cout<<*it<<endl; 错误写法
cout<<it->first<<' '<<it->second<<endl;
}
//map会按照key进行排序,默认从小到大
auto a=2+3;//根据计算结果进行赋值
cout<<a<<endl;
cout<<endl;
//输出方式2:
for(auto i:mp){
cout<<i.first<<' '<<i.second<<endl;
}
//auto的string用法
string str="hello world";
for(auto i:str){
cout<<i;
}
return 0;
}
map容器find()函数↓
#include <bits/stdc++.h>
using namespace std;
int main(){
map<char,int> mp;
mp['a']=123;
mp['b']=234;
mp['c']=345;
mp['d']=456;
map<char,int>::iterator ite;
ite=mp.find('c');
cout<<ite->first<<' '<<ite->second<<endl;
ite=mp.find('p');
if(ite==mp.end()){
cout<<"404 Not found!";
}
else{
cout<<ite->second<<endl;
}
return 0;
}
运行结果

从map中删除一个键值对:erase(键)

浙公网安备 33010602011771号