STL:map映照容器的简单用法(poj 2503 Babelfish)

STL中map映照容器由一个键值和一个映照数据组成,具有一一对应的关系。

结构为:键值--映照数据

        例:  aaa  -- 111

              bbb -- 222

               ccc --  333

键值不允许重复

使用map容器需要头文件#incude<map>

map的创建:map<键值类型,数据类型>

//定义map对象,当前没有任何元素	
	map<string,string> a; 
	//键值类型和数据类型都为字符串 

插入元素:

a["aaa"]="111";
a["bbb"]="222";
a["ccc"]="333";

按照键值输出元素:

ps:map容器值得注意的是它会根据键值从小到大插入。

//向前遍历并将键值升序排序 
map<string,string>::iterator it;
for(it=a.begin();it!=a.end();it++)
{
	cout<<(*it).first<<" : "<<(*it).second<<endl;
}
//后向遍历 :
map<string,string>::reverse_iterator rit;
for(rit=a.rbegin();rit!=a.rend();rit++)
{
        cout<<(*rit).first<<" : "<<(*rit).second<<endl;
}

a.begin()为第一个键值地址

a.end()为最后一个空地址

a.find()的用法:find()用了搜索某个键值,如果搜索到了,和返回该键值所在的迭代器位置,

否则,返回end()迭代器位置。搜索速度极快。

一道关于搜索的例题体现find的用法

 

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.

Input

Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.

Output

Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".

Sample Input

dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

Sample Output

cat
eh
loops

具体代码如下:

#include<iostream>
#include<cstring>
#include<map>
#include<cstdlib>
#include<cstdio>
#define N 100005
using namespace std;
int main()
{
	char str[N],m[N],n[N];
	//定义map对象,当前没有任何元素	
	map<string,string> a; 
	//键值类型和数据类型都为字符串 
	while(gets(str)&&str[0]!='\0')
	{
		sscanf(str,"%s%s",m,n);
		a[n]=m;
	}
	while(gets(str)&&str[0]!='\0')
	{
		if(a.find(str)==a.end())
			cout<<"eh"<<endl;
		else
			cout<<a[str]<<endl;
	}
	return 0;
}

用map实现数字分离:

//键值char类型的数组,数据是int类型数字 
for(int i=0;i<10;i++)
	a['0'+i]=i;
sa="6234";
int sum=0;
for(int i=0;i<4;i++)
	sum+=a[sa[i]];
cout<<sum;

sum等于15;

虽然博主没用过,但是感觉很高级

还可以让

键值int类型的数组,数据是char类型数字 

虽然不知道有啥用吧!

还有二重map的用法:https://blog.csdn.net/qq_42391248/article/details/81631304

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wonder-King

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值