Sam,虽然不清楚您期望的noun/verb
的输入顺序到底是什么,但是您可以利用一个标准容器来保存要排除的单词(以及特殊单词的列表)将会交换订单)。
您已经在使用std::string
。虽然我最初的想法是排除的std::vector<std::string>
,但@paddy提出了一个很好的建议,它将使用std::unordered_set
(或std::set
)进一步简化事情。区别在于基础数据结构,其中std::unordered_set
的恒定时间复杂度比排序的std::set
更好(请参阅std::set与std::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
之后,这可能是从考虑中排除一组单词的最简单方法之一。您还可以将选择的容器用于名词/动词command
。 std::array<std::string,2>
很有意义,但是std::vector
或std::pair
或您最终决定使用的任何其他容器也是如此。
本文链接:https://www.f2er.com/3161901.html