【问题标题】:Is there a way to search an unordered_set using a limited alphabetic range?有没有办法使用有限的字母范围搜索 unordered_set?
【发布时间】: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&lt;char, std::set::iterator&gt;,它映射到集合中以每个字母开头的第一个单词的迭代器。
  • 另一个可能的优化是也检查长度。如果打乱的单词有三个字母,则跳过集合中不包含三个字母的所有单词。
  • 我看不出您的计划将如何提供帮助,但看起来您已将问题简化为 unordered_set 无序,这与输入数据不同。所以....不要放弃订购?您不断变化的需求导致您对数据结构的选择变得不受欢迎。

标签: c++ string search


【解决方案1】:

如果您只需要前 3 个字母的排列,您可以使用 unordered_multiset,其键等于规范排列(例如,排序的前 3 个字母)。但我想你的实际问题不应该只用一种数据结构来解决,而是用几种数据结构来解决,一种数据结构用于存储,其他数据结构用于该存储的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 2019-12-21
    • 2017-04-02
    • 2021-10-26
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多