我想检查 input
是否等于数组中的任何选项。
我该怎么做?我可以不使用很多 ||
运算符就可以做到吗?
//check if any input in herp[] was entered
string input;
string herp[2] = {"Merp", "Derp"}
cin >> input;
if (input == "connect "+herp[0]||"connect "+herp[1]) {
cout << "poopie" << endl;
}
最佳答案
使用std::find
:
#include <algorithm>
if (std::find(std::begin(herp), std::end(herp), input) != std::end(herp)) {
cout << "found it!";
}
此外,在 C++11 中,std::any_of
已添加。您将需要一个谓词函数,此处为 lambda 形式:
if (std::any_of(std::begin(herp), std::end(herp),
[&input](const std::string& str) { return str == input; })) {
cout << "found it!";
}
我还建议您不要使用原始数组,而是使用 std::vector
或 std::array
。它是否在同一个函数中可能并不重要,但是当您传递 C 数组时,它们会退化为指针,然后事情很快就会变得一团糟。
关于c++ - 检查输入是否等于数组中存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18880036/