如何使用单个字母组成单词

use*_*555 5 c++

嘿,我目前有这个代码。它让用户将字符串输入到一个数组中,限制为 5。我计划使用该数组然后从数组中形成单词。我怎样才能做到这一点?

    const int row = 5;
    char array[row];
    char count = 0;
    char letter;
    while (count < 5)
    {
        cout << "Enter a letter: ";
        cin >> letter;
        array[count] = letter;
        count++;
    }
    cout << "Letter inputed" << endl;
    for (count = 0; count < 5; count++)
    {
        cout << array[count] << " " <<  endl;
    }
    system("pause");
Run Code Online (Sandbox Code Playgroud)

pol*_*.ph 1

该解决方案使用关联数组将单词的排序字母映射到具有此类排序字母的单词。因此,可以通过在地图中查找一次来获得答案,这需要渐进O(log N)时间,其中 N 是字典的大小。

创建一个名为dic.txt. 如果您正在使用Visual Studio它,它应该与您的文件位于同一目录中*.cpp。将几个单词以“单词排成一行”的格式放入其中。尝试以下代码:

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;

int main() {
    // Dictionary file is in a "word in a row" format
    map< string, vector<string> > dictionary;
    ifstream dictionary_file("dic.txt");
    if (!dictionary_file.good()) {
        cout << "File doesn't exist" << endl;
        return 0;
    }
    string word;
    while (dictionary_file >> word) {
        string key = word;
        sort(key.begin(), key.end());
        dictionary[key].push_back(word);
    }

    // Read the letters
    string letters;
    cin >> letters;
    if (letters.size() > 5) {
        cout << "Too much letters" << endl;
        return 0;
    }

    // Sort the letters
    sort(letters.begin(), letters.end());

    // Output the answers
    vector<string> & ret = dictionary[letters];
    for (size_t i = 0, ilen = ret.size(); i < ilen; ++i) {
        cout << ret[i] << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

提及这样的解决方案关心您的字母所在的情况。如果您不需要它,您可以在将strtolower单词添加到字典之前以及对字母进行排序之前添加对函数的调用(从 PHP 获得该名称) 。

string strtolowers(string const & word) {
    string ret = word;
    transform(ret.begin(), ret.end(), ret.begin(), tolower);
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

您需要添加<cctype>标头才能使此功能正常工作。