【发布时间】:2020-08-16 14:38:36
【问题描述】:
上下文:我正在用 C++ 编写一个作业,其中用户输入一个单词或一个句子以逐字解读。我有一个充满英语单词的文本文件,我已将其读入 unordered_set 字符串。然后我检查每个输入单词的排列并尝试在 unordered_set 中找到它。未加扰的单词可能性被打印给用户。
问题:文本文件中有很多单词。程序无法正常运行,因为遍历所有排列并在 unordered_set 中寻找匹配项需要很长时间。
可能的解决方案:我想限制要搜索的单词范围,因为文本文件已经按字母顺序排列。例如,如果加扰的词是“cit”,那么这个词的一个排列是“itc”。我想在 unordered_set 中以 i 开头的所有单词搜索“itc”。
这是我目前所拥有的。
void unscramble() {
//issue - too slow, find in range?
string word;
string temp;
ifstream inDictionaryFile("words_alpha.txt");
unordered_set<string> dictionary;
//read dictionary file into a unordered_set
while (getline(inDictionaryFile, temp)) {
auto result = dictionary.insert(temp + " ");
}
cout << "Enter something to unscramble: ";
//find/print out matches for permuations of scrambled words
while (cin>>word) {
do {
word = word + " ";
auto result = dictionary.find(word);
if (result != end(dictionary)) {
cout << setw(10) << word;
}
} while (next_permutation(begin(word), end(word)));
}
}
【问题讨论】:
-
如果你使用了一个有序集合,如果你愿意,一个
std::set,那么你可以保留一个std::map<char, std::set::iterator>,它映射到集合中以每个字母开头的第一个单词的迭代器。 -
另一个可能的优化是也检查长度。如果打乱的单词有三个字母,则跳过集合中不包含三个字母的所有单词。
-
我看不出您的计划将如何提供帮助,但看起来您已将问题简化为
unordered_set无序,这与输入数据不同。所以....不要放弃订购?您不断变化的需求导致您对数据结构的选择变得不受欢迎。