我是靠谱客的博主 哭泣雨,这篇文章主要介绍STL:map映照容器的简单用法(poj 2503 Babelfish),现在分享给大家,希望可以做个参考。

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

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

        例:  aaa  -- 111

              bbb -- 222

               ccc --  333

键值不允许重复

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

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

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

插入元素:

复制代码
1
2
3
a["aaa"]="111"; a["bbb"]="222"; a["ccc"]="333";

按照键值输出元素:

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
//向前遍历并将键值升序排序 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

复制代码
1
2
3
4
5
6
7
8
9
10
dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay

Sample Output

复制代码
1
2
3
4
cat eh loops

具体代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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]!='') { sscanf(str,"%s%s",m,n); a[n]=m; } while(gets(str)&&str[0]!='') { if(a.find(str)==a.end()) cout<<"eh"<<endl; else cout<<a[str]<<endl; } return 0; }

用map实现数字分离:

复制代码
1
2
3
4
5
6
7
8
//键值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;

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

还可以让

复制代码
1
键值int类型的数组,数据是char类型数字

虽然不知道有啥用吧!

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

 

 

 

 

 

 

最后

以上就是哭泣雨最近收集整理的关于STL:map映照容器的简单用法(poj 2503 Babelfish)的全部内容,更多相关STL:map映照容器的简单用法(poj内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部