手机按键程序,其中#include"iostream" #include<string> using namespace std; const int MAXN=101; const string press[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; struct node{ string word;//单词 int prob;//单词的频率 }; node dicWord[20];//词典数组 node words[MAXN]; int dicNum; //str 在词典理出现的概率 inline int checkprob(string str) { int SumProb = 0; for(int i = 0; i < dicNum; i++) { if(dicWord[i].word.substr(0,str.size())==str)//有匹配累计概率,注意子字符串函数用法 { SumProb += dicWord[i].prob; } } return SumProb; } //对输入的数字串,输出所有的可能的单词前缀 void search(string input) { node newWords[MAXN]; int newTotal; int total = 1; //对数字串input的每个字符串进行搜索 for(int i = 0; i < input.size() ; i++) { newTotal = 0;//更新前缀用的 //在上次搜索到的单词前缀(一共total个上)基础上,加一个按键 for(int j = 0;j<total; j++) { //遍历该数字键对应的所有字母 for(int k = 0; k < press[input[i]-'0'].size();k++) { string temp = words[j].word + press[input[i] - '0'][k]; int mark = checkprob(temp); if(mark)//字典里有记录在new中没有的通过吧new付给words消除 { newWords[newTotal].word = words[j].word + press[input[i] - '0'][k]; newWords[newTotal].prob = mark; newTotal++; } } } //查找本次最可能的单词前缀 int best = 0,bestId; for(int i = 0; i < newTotal; i++) { if(newWords[i].prob>best) { best = newWords[i].prob; bestId = i; } } if(best == 0)cout << "MANUALLY"<<endl;//没有匹配的 else cout<<newWords[bestId].word<<endl;//最可能的单词前缀 //备份新的单词条目 把字典里没有的消除 for(int i = 0; i < newTotal; i++) { words[i] = newWords[i]; } total = newTotal; } } int main() { string input; int m; cout << "plese input the dictornory num" <<endl; cin >> dicNum; for(int i = 0; i < dicNum; i++) { cout<<"input dic"<< i<<":"<<endl; cin>>dicWord[i].word>>dicWord[i].prob; } cout<<"输入要查找的次数:"<<endl; cin>>m; for(int i = 0; i < m; i++) { cout << "please input the search stirng nubmer "<<i<<" :"<<endl; cin>>input; input = input.substr(0,input.size() - 1); words[0].word = ""; words[0].prob = 0; search(input); cout<<endl; } return 0; }