给出两个单词的映射关系,然后输入一个单词,查找它所对应的单词,没有的话输出eh
字符串映射,用stl的map可以直接实现,代码量也比较少,关键是处理输入时候,回车表示输出结束,用gets接收
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <cstring> #include <string> #include <map> using namespace std; int main() { int len; char str1[12],str2[12],fstr[30]; string temp; map<string,string> dic; //freopen("E:\\input.txt","r",stdin); while (gets(fstr)) { if (strlen(fstr)==0) break; sscanf(fstr,"%s %s",str1,str2); dic[string(str2)]=string(str1); } while (scanf("%s",&str2)!=EOF) { temp=dic[string(str2)]; if (temp.length()==0) printf("eh\n"); else printf("%s\n",temp.c_str()); } return 0; }
还有一种办法就是使用字符串的hash,然后用拉链法解决冲突,直接看代码吧,这两种方法有待好好掌握,理解都挺容易
#include<cstdio> #include<iostream> #include<string> using namespace std; const int M=20627;//Hash Table的槽数,取质数对解决冲突较为有效 char English[100000][11],Foreign[100000][11]; struct node//Hash Table中的元素类型 { int num;//记录英语数组中的标号 struct node *next; }*link[M]={NULL};//槽中存放一个链表头指针(开散列解决冲突) int ELFlash(char *key)// UNIX 系统ELF字符串散列函数,对字符串的处理一般使用此函数 { unsigned long h=0; while (*key) { h=(h<<4)+*key++; unsigned long g=h & 0xf0000000L; if (g) h^=g>>24; h &= ~g; } return h%M; } int main() { char st[30]; int i,k; node *p; i=0; while (gets(st)) { if (sscanf(st,"%s %s",English[i],Foreign[i])!=2) break;//判断读入词典是否完毕 k=ELFlash(Foreign[i]);//计算Hash函数 p=new node;//建立Hash Table p->num=i; p->next=link[k]; link[k]=p; i++; } while (gets(st)!=NULL) { k=ELFlash(st); p=link[k]; while (p!=NULL)//在Hash Table中查找单词 { if (strcmp(st,Foreign[p->num])==0) break;//若找到则推出 p=p->next; } if (p==NULL) printf("eh\n");//没有找到的情况 else printf("%s\n",English[p->num]); } return 0; }