如何在程序中实现跳字解决方案?

我希望我的程序可以忽略以下单词:用户命令中包含“ the”,“ with”和“ on”。

当前程序仅接受两个单词作为动词和名词字符串作为命令。

string one = "the";
string two = "with";
string three = "on";
string four = "in";

int main()
{
    string noun = "";
    string verb = "";


    getline(cin,verb);
    int x = verb.find(' ');

    if (x > -1) {
        noun = verb.substr(verb.find(" ") + 1);
        verb = verb.substr(0,verb.find(" "));
    }

    if (verb == "living") {
        if (noun == "room") {
            Livingroom();
        }
    }
    else if (verb == "bed") {
        if (noun == "room") {
            Bedroom();
        }
    }


}

我希望程序即使在用户命令中包含前面提到的单词也能正常运行。

zhuzheqi2096409 回答:如何在程序中实现跳字解决方案?

Sam,虽然不清楚您期望的noun/verb的输入顺序到底是什么,但是您可以利用一个标准容器来保存要排除的单词(以及特殊单词的列表)将会交换订单)。

您已经在使用std::string。虽然我最初的想法是排除的std::vector<std::string>,但@paddy提出了一个很好的建议,它将使用std::unordered_set(或std::set)进一步简化事情。区别在于基础数据结构,其中std::unordered_set的恒定时间复杂度比排序的std::set更好(请参阅std::setstd::unordered_set相比。

使用std::unordered设置来排除不需要的单词,可以让您简单地在当前单词上使用.find(word)循环输入命令,并与unordered_set的.end()元素进行比较确定word是否在排除集中。

一个简短的例子可能是:

#include <iostream>
#include <string>
#include <array>
#include <unordered_set>

int main (void) {

    /* unordered set of words to exclude from the command */
    std::unordered_set<std::string> excl = { "in","on","the","with" };
    std::string word;                       /* current word read from input */
    std::array<std::string,2> command;     /* 2 string array (noun/verb) */
    size_t n = 0;                           /* simple counter */

    std::cout << "enter command: ";

    /* read words in command until the 1st two non-excluded words found */
    while (n < command.size() && std::cin >> word) {
        auto search = excl.find(word);      /* search for word in set */
        if (search == excl.end())           /* if word not excluded */
            command.at(n++) = word;         /* add to array,increment count */
    }

    /* output first two non-excluded words */
    std::cout << "\nnoun: " << command.at(0) << 
                "\nverb: " << command.at(1) << '\n';
}

注意:特殊字词的实现(如另一组中的"living""bed")留给您,是否交换名词/动词的顺序也是如此满足您的需求)

使用/输出示例

$ ./bin/set_noun_verb
enter command: in the bed in the room with the candlestick

noun: bed
verb: room

仔细研究。有许多方法可以实现此目的,但是在建议std::unordered_set之后,这可能是从考虑中排除一组单词的最简单方法之一。您还可以将选择的容器用于名词/动词commandstd::array<std::string,2>很有意义,但是std::vectorstd::pair或您最终决定使用的任何其他容器也是如此。

本文链接:https://www.f2er.com/3161901.html

大家都在问