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";

按照键值输出元素:

//向前遍历并将键值升序排序 
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类型数字 
虽然不知道有啥用吧!





猜你喜欢

转载自blog.csdn.net/qq_42391248/article/details/81041669
今日推荐