STL运用之map

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值