在字典上查找数据结构以查找押韵词

时间:2014-11-26 01:55:15

标签: c++ dictionary data-structures trie

我正在处理我的函数,它会从我的字典文本文件中找到含有40,000个单词的押韵单词。举个例子,我输入了akes,它给出了打印的单词“rakes sakes takes”。所以,我知道它需要具有多个变量的数据结构。也许bool会更好地声明isWord而不是int?因此,我正在显示的功能是修改后的功能,因为原始功能只能打印出与用户输入押韵的1个单词。因此,我需要在Trie版本中构建数据结构。说实话,我对数据结构非常糟糕所以请耐心等待。

struct Node
{
    char c;
    Node* letters[26];
    bool isWord;
};

bool findWords(Node*& pTail, char dictionary[][MaxLength + 1], int numberOfDictionaryWords)
{
    Node* pHead;
    pHead = pTail->letters[26];
    bool found = false;
    int first = 0;
    int last = numberOfDictionaryWords - 1;
    int middle = (first + last) / 2;

    while (first <= last)
    {
        if (strncmp(pHead, dictionary[middle], strlen(pTail)) > 0)
        {
            first = middle + 1;
        }
        else if (strncmp(pHead, dictionary[middle], strlen(pTail)) == 0)
        {
            char theWord[MaxLength + 1];
            memcpy(theWord, dictionary[middle], sizeof(char) * (MaxLength + 1));
            cout << "Words(s) found: " << strReverse(theWord) << endl;
            found = true;
            break;
        }
        else
        {
            last = middle - 1;
        }
        middle = (first + last) / 2;
    }
    return found;
}

main()

Node* pTail = NULL;
char dictionary[Rows][MaxLength + 1];
int numberOfWords = 0;
readFile(dictionary, numberOfWords);
sortDictionaryInReverse(dictionary, numberOfWords);
char aWord[MaxLength];
cout << "Enter the suffix to find rhyming words: ";
cin >> aWord;
convertToLowerCase(aWord, strlen(aWord));
strReverse(aWord);

if (findWords(aWord, dictionary, numberOfWords))
{
    cout << "This rhyming word is in the dictionary. \n";
}
else
{
    cout << "This rhyming word is not in the dictionary. \n";
}

1 个答案:

答案 0 :(得分:0)

我认为std::multimap是你最好的选择。

你的非单词将成为关键,而押韵的单词就是价值。

所以你可以这样设置:

std::multimap<std::string, std::string> foo;

foo.insert(std::make_pair("akes", "rakes"));
foo.insert(std::make_pair("akes", "sakes"));
foo.insert(std::make_pair("akes", "takes"));

如果你想说出打印出来的所有押韵&#34; akes&#34;你可以这样做:

std::cout << "akes\n\t";
for(auto i = foo.equal_range("akes"); i.first != i.second; ++i.first){
    std::cout << i.first->second << ' ';
}

如果你想打印出第一个元素,你可以这样做:

std::cout << "akes " << foo.find("akes")->second;