?? wordmapsearch2.cpp
字號:
// Find all anagram groups in a dictionary, and print them to
// standard output stream
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <iterator>
using namespace std;
typedef istream_iterator<string> string_input;
typedef vector<string> WordSet;
typedef map<string,WordSet> WordMap;
// 歡迎界面
void welcome()
{
cout << "******************* 變位詞查找系統Version3******************\n"
<< "在詞典中找出給定的字符串的所有變位詞" << endl;
}
// 讀入詞典文件,構造詞典模型
void readDict(WordMap& enhancedDict)
{
// 從用戶獲取文件名稱
cout << "首先,請輸入詞典的文件名稱:" << endl;
string dictionary_name;
cin >> dictionary_name;
// 打開文件
ifstream ifs(dictionary_name.c_str());
// 讀入異常
if (!ifs.is_open())
{
cerr << "異常:文件"<< dictionary_name
<< "沒有找到 " << endl;
exit(1);
}
cout << "詞典讀入中 ..." << endl;
// 將詞典文件內容讀入到映射enhancedDict中
string word;
string key;
size_t wordCount = 0;
while(ifs)
{
// 逐行讀取詞條
getline(ifs,key);
word = key;
sort(key.begin(),key.end());
// 將詞條和特征碼插入到詞典map模型實例中
enhancedDict[key].push_back(word);
// 更新詞條數目基數
++wordCount;
}
// 輸出詞典屬性
cout << "詞典包含有 "
<< wordCount << " 個單詞\n"<< endl << endl;
#if 0
cout << "詞典占用內存大小為"
<< sizeof(enhancedDict) << "B" << endl << endl;
#endif;
// 關閉文件
ifs.close();
}
// 用于for_each(first,last, printString)
void printString(const string& s)
{
cout << s << " ";
}
// 獲取用戶單詞,查找變位詞并輸出
void analyseAnagram(const WordMap& enhancedDict)
{
cout << "請輸入單詞(或任意字母序列)" << endl;
// 使用輸入流迭代器p接受用戶從標準輸入流cin輸入的字符串,
// 直到用戶輸入流結束標志
for (string_input p(cin); p != string_input(); ++p)
{
cout << "查找輸入單詞的變位詞中..." << endl;
string word = *p;
// 將word變換為它的特征碼
sort(word.begin(),word.end());
// word的變位詞集合
const WordSet& anagramSet = (*(enhancedDict.find(word))).second;
// 直接輸出集合即可
for_each(anagramSet.begin(),anagramSet.end(),printString);
cout << endl;
// 如果集合為空
if(anagramSet.empty())
cout << " 抱歉,沒有找到變位詞\n";
// 提示開始準備新的工作
cout << "\n請輸入下一個單詞 "
<< "(或輸入end-of-file字符終止程序 ) \n"
<< "<end-of-file字符在Windows平臺是Ctrl+Z,UNIX平臺是Ctrl+D>: " << endl;
}
}
int main()
{
welcome();
WordMap dictionary;
readDict(dictionary);
analyseAnagram(dictionary);
system("pause");
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -