STL的使用之map
1.https://vjudge.net/contest/419420#problem/C(map中元素一一对应)
#include<map>
#include<cstring>
#include<iostream>
#include<sstream> //stringstream的头文件
using namespace std;
string s;
map < string , string > maps;//主角map,第一个string是关键字 第二个为值
int main(){
while(getline(cin , s) , s != ""){//不等于""是遇到一行为空时停止输入
stringstream sin(s);
string key,value;
sin >> value >> key;//从s中读取两个字符串
maps[key] = value;//让其中一个字符串作为另一个字符串的关键字
}
while(cin >> s){
map < string , string > ::iterator it = maps.find(s);
//定义一个map类型的迭代器 指向的是maps中是否有s这个关键字存在
//若存在则返回其地址,不存在则返回end()
if(it != maps.end()) cout << maps[s] << '\n';//输出这个关键的值
//也可以用it ->second来进行输出 是取出map中该地址的第二个值
else cout << "eh" << '\n';
}
return 0;
}
2.https://vjudge.net/contest/419420#problem/D(map中以关键词从小到大进行有序排列,可以用begin和end找到最大和最小的关键字,用it迭代器指向最大的时候不能(it - 1) 而是只能使用–it来指向end的前一个位置)
#include<iostream>
#include<map>
#include<cstring>
#include<algorithm>
using namespace std;
map < int , int > maps;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);//关闭同步流,如果读入一行的时候慎关同步流
int com , key , value;
while(cin >> com , com != 0){
if(com == 1){
cin >> value >> key;
maps[key] = value;
}
else{
if(maps.empty()){
cout << "0" << '\n';
continue;
}
if (com == 2){
map < int , int >::iterator it = maps.end();//指向最大的后一个位置
cout << (--it) -> second << '\n';//不能用it - 1 只能--it
maps.erase(it);//删除掉迭代器it所指向的元素
}
else {
map < int , int >::iterator it = maps.begin();//指向最小
cout << it -> second << '\n';
maps.erase(it);
}
}
}
return 0;
}