词典(map)题解

题目描述

你旅游到了一个国外的城市。那里的人们说的外国语言你不能理解。不过幸运的是,你有一本词典可以帮助你。

输入格式

首先输入一个词典,词典中包含不超过100000个词条,每个词条占据一行。每一个词条包括一个英文单词和一个
外语单词,两个单词之间用一个空格隔开。而且在词典中不会有某个外语单词出现超过两次。词典之后是一个空行,
然后给出一个由外语单词组成的文档,文档不超过100000行,而且每行只包括一个外语单词。输入中出现单词只包
括小写字母,而且长度不会超过10。

输出格式

在输出中,你需要把输入文档翻译成英文,每行输出一个英文单词。如果某个外语单词不在词典中,就把这个单词
翻译成“eh”。

样例输入

og ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay

样例输出

cat
eh
loops

这道题其实并不难,用 map就可以轻松的解决了。解释就附在代码上吧~(博主的一贯风格)


这里先介绍一个东东:
istringstream


#include <cstdio>
#include <cmath>
#include <string>
#include <map>
#include <iostream>
#include <sstream>
using namespace std;
map <string, string> book;//定义一个 map, 在 两个字符串之间建立一个映射
string str1, str2, str3;//用于输入
int main() {
	while (getline(cin, str1)) {//getline 用于读入一整行
		if (str1.length() == 10) {//假如说读到换行,就跳出循环(换行的 ASCLL 码是10),开始查询操作
			break;
		}
		istringstream fcin(str1);//如上
		fcin >> str2 >> str3;
		book[str3] = str2;//读入
	}
	
	 while(getline(cin, str1)) {//输入要输入的字符串  
        int i = book.count(str1);  
        if (i > 0)  
            cout << book[str1] << endl;  //找到了,输出
        else  
            cout << "eh" << endl;  //没有
    }  
    
	return 0;
}

文章就到这里了,写的不好的地方还请多多指教!
拜拜!

原文地址:https://www.cnblogs.com/cqbzyanglin/p/13509282.html