多个 if-else 测试的更简单方法



我有一个字符串,如果字符串值与给定的一组单词匹配,我想执行if语句(比如猿,吃,睡,芒果......

我可以做:-

if(name=="ape" || name=="eat".............)

有没有更简单的方法可以做到这一点?

我想只使用如果-否则。

对单词数组进行贴花,然后使用标准算法std::findstd::any_of

例如

const char * words[] =
{
"ape", "eat", "sleep", "mango"
}; 
if ( std::find( std::begin( words ), std::end( words ), name ) != std::end( words ) )
{
//...
}

如果要声明排序数组,则可以使用标准算法std::binary_search

这是一个演示程序

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main() 
{
const char * words[] =
{
"eat", "ape", "mango", "sleep" 
};
std::string name( "mango" );
if ( std::binary_search( std::begin( words ), std::end( words ), name ) )
{
std::cout << name << " is a correct namen";
}
return 0;
}

它的输出是

mango is a correct name

或者将单词放在标准容器中,例如std::set并使用容器的 find 方法。

如果你想把它保留为只有ifelse而不添加任何东西,那就没有了。

否则,您可以使用std::unordered_set,用这些单词填充它并使用find()

for(auto pattern: {"ape", "eat"}) {
if(name == pattern) {
// all the consequences here
break;
}
}

或者,在热路径上,您可以使用类似哈希集的东西:

static const std::unordered_set<std::string> words{"ape", "eat"};
if(words.find(name) != words.end()) {
}

只要确保它是一个static const,不要每次都重新初始化它。如果你有一套真正的模式可以允许,那可能会更好。

您可以使用字符串unordered_set并搜索名称。 像这样:

#include <iostream>
#include <unordered_set>
#include <string>
#include <algorithm>
int main()
{
std::unordered_set<std::string> values = { "ape", "stuff", "dude" };

std::string name = "ape";
if (std::find(std::begin(values), std::end(values), name) != std::end(values)) {
std::cout << "found it";
} else {
std::cout << "no found it";
}
return 0;
}

感谢松布雷罗鸡提到unordered_set。我默认为矢量。 可能有一些带有 constexpr unordered_set 的 C++17/C++20 版本。但我把这个留给别人。

如果您不关心性能,但想要最少的代码,请构建一个 std::string,其中包含由不同分隔符分隔的所有单词,也在开头和结尾。然后std::string::find()您的搜索词也用分隔符括起来:

static const std::string words("^ape^stuff^dude^");
if (words.find("^"+name+"^") != words.npos)
std::cout << "found it";

或者省去 const std::string 并使用 clib 中的strstr

最新更新